TCPClient有时会收到空字节数组

目前正在使用套接字开发一个简单的消息服务器,有时TCPClient接收正确的字节数,但每个字节为0。

这是发件人代码。

try { //c.clientSocket.NoDelay = true; // Send back an OK var clientStream = c.clientSocket.GetStream(); var Response = JsonConvert.SerializeObject(new Packet("SERVER", c.ClientName, new List() { new Payload(MessageLibrary.Commands.OK, null) })); var msg = System.Text.Encoding.ASCII.GetBytes(Response); clientStream.Write(msg, 0, msg.Length); } catch (Exception ex) { if (ExceptionRaised != null) ExceptionRaised(c.ClientName, ex); } 

Response = "{\"TimeStamp\":\"2016-03-18T08:15:15.0881326+00:00\",\"Sender\":\"SERVER\",\"Payload\":[{\"Command\":\"OK\",\"CommandValue\":\"\"}],\"Destination\":\"GBCO0101\"}"

消息包含139个字节

所以这似乎没问题,这是接收代码。

  static void OnDataRecieved(IAsyncResult result) { TcpClient client = result.AsyncState as TcpClient; // Get a stream object for reading and writing try { NetworkStream stream = client.GetStream(); int ReadBytes = stream.EndRead(result); if (ReadBytes == 0) { // Client gone Console.WriteLine("Server lost"); } else { // Translate data bytes to a ASCII string. var data = System.Text.Encoding.ASCII.GetString(ClientReadBuffer, 0, ReadBytes); ClientReadBuffer = new byte[ClientReadBuffer.Length]; stream.BeginRead(ClientReadBuffer, 0, ClientReadBuffer.Length, new AsyncCallback(OnDataRecieved), client); ProcessData(data); } } catch (Exception ex) { Console.WriteLine("lost connection"); Console.WriteLine(ex.Message); } } 

如果我看一下ProcessData(data); 我可以看到data = "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"

ReadBytes = 139

所以正确的字节数似乎是正确的,但数据本身是错误的。 是什么导致这种情况?

这不太可能。

你真的在第一个stream.BeginRead()上使用ClientReadBuffer (它不包含在上面的代码中)? 你可能有一个不以同样方式读取的地方。

为什么要为每次读取创建一个新的实例? 浪费资源。 只需重复使用它。

另一件事是TCP是基于流的。 不要指望收到的字节与您发送的缓冲区匹配。 例如,请参阅此问题 。