tcpclient接收数据不正确

不确定这是TCPClient还是其他什么,我使用网络嗅探器检查从服务器发送和接收的内容,数据是否正确但是我的软件接收数据不正确。

让我解释一下,我发送一个查询字节(05)我得到一个确认回(06)然后我发送一些以9B字节开头的数据,一旦发送,我应该接收一个06字节然后在那个字节之后我应该得到一个C5字节,但根据我的软件,我得到另一个06字节,根据嗅探器不是这种情况!

byte[] buff; if (!this.isConnected()) this.connect(); NetworkStream gs = _Socket.GetStream(); gs.Write(enq, 0, enq.Length); gs.Flush(); outputByte(enq, "Trans"); //outputs ---> 05 buff = new byte[1]; gs.Read(buff, 0, buff.Length); gs.Flush(); outputByte(buff, "Rec");// outputs  with above byte information gs.Write(data, 0, data.Length); gs.Flush(); buff = new byte[1]; gs.Read(buff, 0, buff.Length); gs.Flush(); // this is the first receive of 06 outputByte(buff, "Rec");//outputs <--- 06 if (buff[0] == 0x06) { gs.Flush(); Console.WriteLine("fdsfsdfs"); byte[] resp = new byte[5]; gs.Read(resp, 0, resp.Length); gs.Flush(); //this outputs <--- 06 but it should be showing <--- c5000100c4 outputByte(buff, "Rec"); gs.Write(ack, 0, ack.Length); outputByte(ack, "Trans"); gs.Flush(); } } 

根据嗅探器,这是应该发生的事情

 ---> 05  9b008000000080000009671101494d414745310000000000000000000000000000000153756d6d617279000000000000000000000000000000000000000000000000000002080000080000001f090100040a100012011f000000050001000000000012101e0e1e54657374696e67100012011f000000050001000000000012100d000090 <--- 06 <--- c5000100c4 

根据软件,这就是正在发生的事情

 ---> 05  9b008000000080000009671101494d414745310000000000000000000000000000000153756d6d617279000000000000000000000000000000000000000000000000000002080000080000001f090100040a100012011f000000050001000000000012101e0e1e54657374696e67100012011f000000050001000000000012100d000090 <--- 06 <--- 06 

有任何想法吗? 如果您对如何改进代码有任何建议,我将不胜感激

这里:您输出错误的缓冲区:

  gs.Read(resp, 0, resp.Length); gs.Flush(); outputByte(buff, "Rec"); <==== should be "resp" 

然而!!!

你的所有阅读电话都被打破了; 它们必须处理返回值, 尤其是在读取多个字节时。 数据包碎片会破坏您的代码。

正确的“精确读取[n]字节”方法将是:

 public static void ReadExact(this Stream stream, byte[] buffer, int offset, int count) { int read; while(count > 0 && (read = stream.Read(buffer, offset, count)) > 0) { count -= read; offset += read; } if(count != 0) throw new EndOfStreamException(); } 

然后:

 gs.ReadExact(resp, 0, resp.Length); 

将正确填充,如果流中没有足够的数据,则会出错。