Data loss TCP IP C#

前端 未结 2 1407
没有蜡笔的小新
没有蜡笔的小新 2021-01-14 21:43

Here\'s my code:

private void OnReceive(IAsyncResult result)
{
NetStateObject state = (NetStateObject)result.AsyncState;

Socket client = state.Socket;

int          


        
2条回答
  •  终归单人心
    2021-01-14 22:25

    TCP is a stream protocol. It has no concept of packets. A single write call can be sent in multiple packets, and multiple write calls can be put into the same packet. So you need to implement your own packetizing logic on top of TCP.

    There are two common ways to packetize:

    1. Delimiter characters, this is usually used in text protocols, with the new-line being a common choice
    2. Prefix the length to each packet, usually a good choice with binary protocols.

    You store the size of a logical packet at the beginning of that packet. Then you read until you received enough bytes to fill the packet and start deserializing.

提交回复
热议问题