C# Socket TCP Send, messages getting “stuck”

前端 未结 5 818
感情败类
感情败类 2021-01-15 10:45

This is a bit of an odd one and apologies if I don\'t explain it very well.

I am using the following simple code to send messages that I have popped off a queue, usi

5条回答
  •  独厮守ぢ
    2021-01-15 11:22

    TCP is a stream protocol. You cannot assume that the 'packets' you Send() are going to be delivered and received in tact. At the transmitting end, the Nagle algorithm tries to combine the data that was written in separate Send() calls to optimize delivery of the data. At the receiving end you'll Read() what is stored in the TCP buffer. If will be a combination of the transmitted packets if there's any delay. This is further complicated by the routers in between the transmitter and receiver, they are allowed to fragment an IP packet, turning a large one into multiple small ones, to accommodate the transmission channel's maximum packet size (MTU).

    In other words, there is no reliable way to ensure that the packets are delivered the way they were sent. A simple workaround for this is first transmitting the size of the packet. At the receiving end you first read that size, then know how to count off the received bytes to reconstruct the packet.

提交回复
热议问题