简体   繁体   English

Socket ReceiveAsync 合并数据包

[英]Socket ReceiveAsync merging packets

I intend to receive packets of data over a socket but since they are sent from the sender with a high frequency a number of them get packed into a single byte array.我打算通过套接字接收数据包,但由于它们是从发送者以高频率发送的,因此它们中的一些被打包成一个单byte数组。 SocketAsyncEventArgs.Buffer then holds multiple packets, even though they were sent separately (verified using wireshark ). SocketAsyncEventArgs.Buffer然后保存多个数据包,即使它们是单独发送的(使用wireshark验证)。

I have already tried to queue the incoming packets and asynchronously work them off, but still I get the same result.我已经尝试对传入的数据包进行排队并异步处理它们,但我仍然得到相同的结果。

What could be reason for this behaviour?这种行为可能是什么原因?

This is how TCP works.这就是 TCP 的工作原理。 TCP connection is a bi-directional stream of bytes , and you have to treat it as such. TCP 连接是字节的双向 stream ,你必须这样对待它。 Single send from one end might result in multiple reads on the receiving side, and vice versa, multiple sends might end up in a single read, and application message boundaries are not preserved by the transport.来自一端的单次发送可能会导致接收端进行多次读取,反之亦然,多次发送可能会以单次读取结束,并且传输不会保留应用程序消息边界。

You have to buffer the input until you know you have a complete application message.您必须缓冲输入,直到您知道您有完整的应用程序消息。 Common approaches are:常见的方法是:

  • fixed length messages,固定长度的消息,
  • pre-pending length in front of the message,消息前面的前置长度,
  • delimiting the stream with special "end-of-message" separator.用特殊的“消息结束”分隔符分隔 stream。

I might be mistaking, but isn't this the Naggle algorithm kicking in?我可能弄错了,但这不是 Naggle 算法的作用吗? Your sockets should have a flag that disables this.您的 sockets 应该有一个禁用此功能的标志。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM