我的服务器端程序:
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.IO;
namespace tcpserver
{
/// <summary>
/// Form1 的摘要说明。
/// </summary>
public class Form1 : System.Windows.Forms.Form
{
/// <summary>
/// 必需的设计器变量。
/// </summary>
private System.ComponentModel.Container components = null;
int port = 8000; //定义侦听端口号 private Thread thThreadRead; //创建线程,用以侦听端口号,接收信息
private TcpListener tlTcpListen; //侦听端口号
private bool blistener = true; //设定标示位,判断侦听状态 private NetworkStream nsStream; //创建接收的基本数据流   private StreamReader srRead;
private StreamWriter swWriter;
private System.Windows.Forms.ListBox listBox1;
private System.Windows.Forms.Button button1;
private System.Windows.Forms.StatusBar statusBar1;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Button button2;
private System.Windows.Forms.TextBox textBox2; private TcpClient tcClient ; public Form1()
{
//
// Windows 窗体设计器支持所必需的
//
InitializeComponent(); //
// TODO: 在 InitializeComponent 调用后添加任何构造函数代码
//
} /// <summary>
/// 清理所有正在使用的资源。
/// </summary>
protected override void Dispose( bool disposing )
{
try  {  tlTcpListen.Stop(); //关闭侦听  nsStream.Close(); srRead.Close();//释放资源 
swWriter.Close(); thThreadRead.Abort();//中止线程  }  catch{}
if( disposing )
{
if (components != null) 
{
components.Dispose();
}
}
base.Dispose( disposing );
} #region Windows 窗体设计器生成的代码
/// <summary>
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
/// 此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.listBox1 = new System.Windows.Forms.ListBox();
this.button1 = new System.Windows.Forms.Button();
this.statusBar1 = new System.Windows.Forms.StatusBar();
this.textBox2 = new System.Windows.Forms.TextBox();
this.label1 = new System.Windows.Forms.Label();
this.button2 = new System.Windows.Forms.Button();
this.SuspendLayout();
// 
// listBox1
// 
this.listBox1.ItemHeight = 12;
this.listBox1.Location = new System.Drawing.Point(16, 24);
this.listBox1.MultiColumn = true;
this.listBox1.Name = "listBox1";
this.listBox1.Size = new System.Drawing.Size(432, 124);
this.listBox1.TabIndex = 0;
// 
// button1
// 
this.button1.Location = new System.Drawing.Point(176, 160);
this.button1.Name = "button1";
this.button1.TabIndex = 1;
this.button1.Text = "开始服务";
this.button1.Click += new System.EventHandler(this.button1_Click);
// 
// statusBar1
// 
this.statusBar1.Location = new System.Drawing.Point(0, 384);
this.statusBar1.Name = "statusBar1";
this.statusBar1.Size = new System.Drawing.Size(464, 22);
this.statusBar1.TabIndex = 2;
this.statusBar1.Text = "statusBar1";
// 
// textBox2
// 
this.textBox2.Location = new System.Drawing.Point(112, 224);
this.textBox2.Name = "textBox2";
this.textBox2.Size = new System.Drawing.Size(136, 21);
this.textBox2.TabIndex = 3;
this.textBox2.Text = "";
// 
// label1
// 
this.label1.Location = new System.Drawing.Point(0, 224);
this.label1.Name = "label1";
this.label1.TabIndex = 4;
this.label1.Text = "发送内容:";
// 
// button2
// 
this.button2.Location = new System.Drawing.Point(304, 224);
this.button2.Name = "button2";
this.button2.TabIndex = 5;
this.button2.Text = "发送";
this.button2.Click += new System.EventHandler(this.button2_Click);
// 
// Form1
// 
this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
this.ClientSize = new System.Drawing.Size(464, 406);
this.Controls.Add(this.button2);
this.Controls.Add(this.label1);
this.Controls.Add(this.textBox2);
this.Controls.Add(this.statusBar1);
this.Controls.Add(this.button1);
this.Controls.Add(this.listBox1);
this.Name = "Form1";
this.Text = "Form1";
this.ResumeLayout(false); }
#endregion /// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main() 
{
Application.Run(new Form1());
}
private void Listen ( )  {  try  {  tlTcpListen = new TcpListener(port);//以8000端口号来初始化TcpListener实例 tlTcpListen.Start ( ) ; //开始监听 statusBar1.Text = "正在监听..." ;  tcClient = tlTcpListen.AcceptTcpClient(); //通过TCP连接请求 nsStream = tcClient.GetStream(); //获取用以发送、接收数据的网络基础数据流 srRead=new StreamReader(nsStream);//以得到的网络基础数据流来初始化StreamReader实例 swWriter=new StreamWriter(nsStream); statusBar1.Text = "已经连接!";   while( blistener ) //循环侦听 {  string sMessage = srRead.ReadLine();//从网络基础数据流中读取一行数据  if ( sMessage == "STOP" ) //判断是否为断开TCP连接控制码 {  tlTcpListen.Stop(); //关闭侦听 nsStream.Close(); //释放资源 srRead.Close();  statusBar1.Text = "连接已经关闭!" ;  thThreadRead.Abort(); //中止线程 return;  }   string sTime = DateTime.Now.ToShortTimeString ( ) ; //获取接收数据时的时间 listBox1.Items.Add ( sTime + " " + sMessage ) ;  }  }  catch ( System.Security.SecurityException )  {  MessageBox.Show ( "侦听失败!" , "错误" ) ;  }  }
private void button1_Click(object sender, System.EventArgs e)
{
thThreadRead = new Thread ( new ThreadStart ( Listen ) );
thThreadRead.Start();//启动线程           
button1.Enabled=false;  } private void button2_Click(object sender, System.EventArgs e)
{
if (textBox2.Text !="")  { 
swWriter.WriteLine(textBox2.Text);//刷新当前数据流中的数据
swWriter.Flush(); 
}  else  {
MessageBox.Show("发送信息不能为空!","错误提示!"); 
}

}
}
}

解决方案 »

  1.   

    客户端程序:
    using System;
    using System.Drawing;
    using System.Collections;
    using System.ComponentModel;
    using System.Windows.Forms;
    using System.Data;
    using System.IO;
    using System.Threading;
    using System.Net;
    using System.Net.Sockets;namespace tcpclient
    {
    /// <summary>
    /// Form1 的摘要说明。
    /// </summary>
    public class Form1 : System.Windows.Forms.Form
    {
    private StreamWriter swWriter; //用以向网络基础数据流传送数据  private NetworkStream nsStream; //创建发送数据的网络基础数据流  private TcpClient tcpClient; private StreamReader sr;
    public string recvs; private System.Windows.Forms.Label label1;
    private System.Windows.Forms.Label label2;
    private System.Windows.Forms.Button button1;
    private System.Windows.Forms.Button button2;
    private System.Windows.Forms.TextBox textBox1;
    private System.Windows.Forms.TextBox textBox2;
    private System.Windows.Forms.StatusBar statusBar1; private bool tcpConnect = false;
    private System.Windows.Forms.ListBox listBox1;
    private System.Windows.Forms.Label label3; //定义标识符,用以表示TCP连接是否建立 /// <summary>
    /// 必需的设计器变量。
    /// </summary>
    private System.ComponentModel.Container components = null; public Form1()
    {
    //
    // Windows 窗体设计器支持所必需的
    //
    InitializeComponent(); //
    // TODO: 在 InitializeComponent 调用后添加任何构造函数代码
    //
    } /// <summary>
    /// 清理所有正在使用的资源。
    /// </summary>
    protected override void Dispose( bool disposing )
    {
    if (tcpConnect) 
    {  swWriter.WriteLine ( "STOP" ) ; //发送控制码   swWriter.Flush (); //刷新当前数据流中的数据  
    nsStream.Close (); //清除资源 swWriter.Close ();  } 
    if( disposing )
    {
    if (components != null) 
    {
    components.Dispose();
    }
    }
    base.Dispose( disposing );
    } #region Windows 窗体设计器生成的代码
    /// <summary>
    /// 设计器支持所需的方法 - 不要使用代码编辑器修改
    /// 此方法的内容。
    /// </summary>
    private void InitializeComponent()
    {
    this.label1 = new System.Windows.Forms.Label();
    this.label2 = new System.Windows.Forms.Label();
    this.button1 = new System.Windows.Forms.Button();
    this.button2 = new System.Windows.Forms.Button();
    this.textBox1 = new System.Windows.Forms.TextBox();
    this.textBox2 = new System.Windows.Forms.TextBox();
    this.statusBar1 = new System.Windows.Forms.StatusBar();
    this.listBox1 = new System.Windows.Forms.ListBox();
    this.label3 = new System.Windows.Forms.Label();
    this.SuspendLayout();
    // 
    // label1
    // 
    this.label1.Location = new System.Drawing.Point(40, 96);
    this.label1.Name = "label1";
    this.label1.TabIndex = 0;
    this.label1.Text = "连接IP";
    // 
    // label2
    // 
    this.label2.Location = new System.Drawing.Point(40, 136);
    this.label2.Name = "label2";
    this.label2.TabIndex = 1;
    this.label2.Text = "发送内容";
    // 
    // button1
    // 
    this.button1.Location = new System.Drawing.Point(48, 168);
    this.button1.Name = "button1";
    this.button1.TabIndex = 2;
    this.button1.Text = "连接";
    this.button1.Click += new System.EventHandler(this.button1_Click);
    // 
    // button2
    // 
    this.button2.Location = new System.Drawing.Point(176, 168);
    this.button2.Name = "button2";
    this.button2.TabIndex = 3;
    this.button2.Text = "发送";
    this.button2.Click += new System.EventHandler(this.button2_Click);
    // 
    // textBox1
    // 
    this.textBox1.Location = new System.Drawing.Point(176, 88);
    this.textBox1.Name = "textBox1";
    this.textBox1.Size = new System.Drawing.Size(192, 21);
    this.textBox1.TabIndex = 4;
    this.textBox1.Text = "textBox1";
    // 
    // textBox2
    // 
    this.textBox2.Location = new System.Drawing.Point(176, 136);
    this.textBox2.Name = "textBox2";
    this.textBox2.Size = new System.Drawing.Size(192, 21);
    this.textBox2.TabIndex = 5;
    this.textBox2.Text = "textBox2";
    // 
    // statusBar1
    // 
    this.statusBar1.Location = new System.Drawing.Point(0, 344);
    this.statusBar1.Name = "statusBar1";
    this.statusBar1.Size = new System.Drawing.Size(520, 22);
    this.statusBar1.TabIndex = 6;
    this.statusBar1.Text = "statusBar1";
    // 
    // listBox1
    // 
    this.listBox1.ItemHeight = 12;
    this.listBox1.Location = new System.Drawing.Point(56, 248);
    this.listBox1.MultiColumn = true;
    this.listBox1.Name = "listBox1";
    this.listBox1.Size = new System.Drawing.Size(328, 88);
    this.listBox1.TabIndex = 7;
    // 
    // label3
    // 
    this.label3.Location = new System.Drawing.Point(48, 224);
    this.label3.Name = "label3";
    this.label3.TabIndex = 8;
    this.label3.Text = "接收的数据:";
    // 
    // Form1
    // 
    this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
    this.ClientSize = new System.Drawing.Size(520, 366);
    this.Controls.Add(this.label3);
    this.Controls.Add(this.listBox1);
    this.Controls.Add(this.statusBar1);
    this.Controls.Add(this.textBox2);
    this.Controls.Add(this.textBox1);
    this.Controls.Add(this.button2);
    this.Controls.Add(this.button1);
    this.Controls.Add(this.label2);
    this.Controls.Add(this.label1);
    this.Name = "Form1";
    this.Text = "Form1";
    this.ResumeLayout(false); }
    #endregion /// <summary>
    /// 应用程序的主入口点。
    /// </summary>
    [STAThread]
    static void Main() 
    {
    Application.Run(new Form1());
    } private void button1_Click(object sender, System.EventArgs e)
    {
    IPAddress ipRemote ;  try  {  ipRemote = IPAddress.Parse ( textBox1.Text ) ;  }  catch //判断给定的IP地址的合法性 {  MessageBox.Show ( "输入的IP地址不合法!" , "错误提示!" ) ;  return ;  }   IPHostEntry ipHost ;  try  {  ipHost = Dns.Resolve ( textBox1.Text ) ;   }  catch //判断IP地址对应主机是否在线 {  MessageBox.Show ("远程主机不在线!" , "错误提示!" ) ;  return ;  }   string sHostName = ipHost.HostName ;  try  {  TcpClient tcpClient = new TcpClient(sHostName,8000);//对远程主机的8000端口提出TCP连接申请 nsStream = tcpClient.GetStream();//通过申请,并获取传送数据的网络基础数据流   swWriter = new StreamWriter(nsStream);//使用获取的网络基础数据流来初始化StreamWriter实例
    sr=new StreamReader(nsStream);
    Thread recvthread=new Thread(new ThreadStart(recvdata));
    recvthread.Start(); button1.Enabled = false ;  button2.Enabled = true ;  tcpConnect = true ;  statusBar1.Text = "已经连接!" ;  }  catch  {  MessageBox.Show ( "无法和远程主机8000端口建立连接!" , "错误提示!" ) ;  return ;  } 
    }
    public void recvdata()
    {
    recvs=sr.ReadLine();
    listBox1.Items.Clear();
    listBox1.Items.Add(recvs);
    } private void button2_Click(object sender, System.EventArgs e)
    {
    if (textBox2.Text !="")  {  swWriter.WriteLine(textBox2.Text);//刷新当前数据流中的数据 swWriter.Flush();  }  else  { MessageBox.Show("发送信息不能为空!","错误提示!");  } } }
    }
    客户端向服务器端发送 没有问题。
    但是 服务器向客户端发消息,第一次 没有问题,但是 第二次  就不可以了?
    请 大家 帮帮忙?
      

  2.   

    public void recvdata()
    {
    recvs=sr.ReadLine();
    listBox1.Items.Clear();
    listBox1.Items.Add(recvs);
    Thread recvthread=new Thread(new ThreadStart(recvdata));
    recvthread.Start();
    }每次听取的时候都要再打开一个线程继续等待听取. 不然一次就结束了.
      

  3.   

    给你一段代码... 注意最后的线程        private void SecThreadProc()
            {
                int port = 2005;
                //this.m_ServerIP = Dns.GetHostAddresses(Dns.GetHostName())[0]; 
                 //string host = "127.0.0.1";
                // string host = Dns.GetHostAddresses(Dns.GetHostName())[0]; 
               // IPAddress ip = IPAddress.Parse(host);
                IPAddress ip = Dns.GetHostAddresses(Dns.GetHostName())[0];
                IPEndPoint ipe = new IPEndPoint(ip, port);
                Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//创建一个Socket类
                s.Bind(ipe);//绑定2005端口
                s.Listen(0);//开始监听
                //Console.WriteLine("Wait for connect");            Socket temp = s.Accept();//为新建连接创建新的Socket。
                //Console.WriteLine("Get a connect");
                string recvStr = "";
                byte[] recvBytes = new byte[1024];
                int bytes;
                bytes = temp.Receive(recvBytes, recvBytes.Length, 0);//从客户端接受信息
                recvStr += Encoding.ASCII.GetString(recvBytes, 0, bytes);
                //Console.WriteLine("Server Get Message:{0}", recvStr);//把客户端传来的信息显示出来
               // MessageBox.Show(recvStr);
                if (recvStr == "IDC_PAINT")
                {
                    PDC_PRINT();
                }            if (recvStr == "CLOSE_WINDOWS")
                {
                    close_Windows();
                }
                string sendStr = "Ok!Client Send Message Sucessful!";
                byte[] bs = Encoding.ASCII.GetBytes(sendStr);
                temp.Send(bs, bs.Length, 0);//返回客户端成功信息
                temp.Close();
                s.Close();            Thread SecThread = new Thread(new ThreadStart(SecThreadProc));
                SecThread.Start();
            }
      

  4.   

    服务端:线程池+socket+tcp
    客户端:单线程+socket+tcp
      

  5.   

    zhaochong12(笨鸟)  兄弟,向你这样可 又出现了新的问题啊!程序退出是时候,不停的向服务器发送 空消息! 并且 在程序异常退出!
      

  6.   

    先解决你最新的问题闭时这样关闭,选关闭与对方已经建立的连接,比如客户端你连接的套接字是Tcpclient socket = new Tcpclient (……)(具体的我不写)socket.Client.close();socket.close();
    另外你上面的程序中多次出现在一个线程中去直接操纵另一个线程的控件的问题,这样是不允许的,容易发生死锁,如果想操纵可以用委托
    而且你的服务器端只可以接受一个客户端的连接如果接两个以上的话发送信息客户端没办法收到
      

  7.   

    有 这方面的 程序吗? 发给我一个,邮箱:[email protected]
    谢谢了!