笔记-TCPCLIENT
byte[] myReadBuffer = new byte[1024]; private void ReceiveMessage() { try { tcpClient = new System.Net.Sockets.TcpClient("192.168.1.3", 8888);//创建TcpClient对象实例 } catch (Exception le) { } netStream = tcpClient.GetStream();//得到网络流 if (netStream.CanWrite) { byte[] myWriteBuffer = Encoding.ASCII.GetBytes("Are you receiving this message?"); netStream.BeginWrite(myWriteBuffer, 0, myWriteBuffer.Length, new AsyncCallback(myWriteCallBack), netStream); allDone.WaitOne(); } else { Console.WriteLine("Sorry. You cannot write to this NetworkStream."); } if (netStream.CanRead) { netStream.BeginRead(myReadBuffer, 0, myReadBuffer.Length,myReadCallBack,netStream); allDone.WaitOne(); } else { Console.WriteLine("Sorry. You cannot read from this NetworkStream."); } } public void myWriteCallBack(IAsyncResult ar) { NetworkStream myNetworkStream = (NetworkStream)ar.AsyncState; myNetworkStream.EndWrite(ar); allDone.Set(); } public void myReadCallBack(IAsyncResult ar) { StringBuilder myCompleteMessage = new StringBuilder(); NetworkStream myNetworkStream = (NetworkStream)ar.AsyncState; int numberOfBytesRead; numberOfBytesRead = myNetworkStream.EndRead(ar); string str = Encoding.ASCII.GetString(myReadBuffer, 0, numberOfBytesRead); myCompleteMessage.AppendFormat("{0}", str); // message received may be larger than buffer size so loop through until you have it all. while (myNetworkStream.DataAvailable) { myNetworkStream.BeginRead(myReadBuffer, 0, myReadBuffer.Length,new AsyncCallback(myReadCallBack), myNetworkStream); // } // Print out the received message to the console. TextBox2.Text = myCompleteMessage.ToString(); allDone.Set(); }