日期:2014-05-18 浏览次数:21038 次
//初始化TcpListener //启动一个新的线程,假定该线程的目标函数是ThreadATargetFun(object _TcpListener) //线程启动的时候要把TCPListener传递到目标函数中。 //在该函数中: //先把object强制转换成TCPListener _TcpListener.Start() while(true) { TcpClient ClientTCPClient = _TCPListen.AcceptTcpClient(); Thread ReadClientConnectThread = new Thread(new ParameterizedThreadStart(ReadClientDataThreadFun)); //ReadClientDataThreadFun(object ClientTCPClient) ReadClientConnectThread.Start(_tmpdtuclient);//传递该客户端 } /// <summary> /// 接收客户端发送的数据的线程的目标函数 /// </summary> protected void ReadClientDataThreadFun(object obj) { //要增加自己的try、catch模块,判断是否客户端断开连接,或者网络中断等故障 // //强制转换成TCPClient,获取网络流 while(true) { int _readBytesCount = -1; byte[] _receiveBuffer = new byte[512]; _readBytesCount = _tmpdtuclient.DTUNetworkStream.Read(_receiveBuffer, 0, _receiveBuffer.Length);//如果客户端断开了连接,则read方法会立即返回0 if (_readBytesCount == 0) { //客户端退出连接。 SetMSG("客户端退出连接!客户端信息:" + _tmpdtuclient.DTUTCPClient.Client.RemoteEndPoint.ToString()); Thread.CurrentThread.Abort(); } //读写网络流 } }
------解决方案--------------------
private void StartListen() [align=left]{ this.TcpListener = new TcpListener(19808); this.TcpListener.Start(); while( true ) { TcpClient TcpClient = this.TcpListener.AcceptTcpClient(); NetworkStream MyStream = TcpClient.GetStream(); byte [] bytes = new byte[2048]; int bytesRead = MyStream.Read(bytes,0,bytes.Length); string message = System.Text.Encoding.UTF8.GetString(bytes,0,bytesRead); } } private void MainForm_Load(object sender, System.EventArgs e