C# Socket BeginReceive / EndReceive capturing multiple messages

前端 未结 3 627
野的像风
野的像风 2021-01-21 04:09

Problem:

When I do something like this:

for (int i = 0; i < 100; i++)
{
    SendMessage( sometSocket, i.ToString());
    Thread.Sleep(250); // works          


        
3条回答
  •  孤独总比滥情好
    2021-01-21 04:59

    This is expected behaviour. A TCP socket represents a linear stream of bytes, not a sequence of well-delimited “packets”. You must not assume that the data you receive is chunked the same way it was when it was sent.

    Notice that this has two consequences:

    1. Two messages may get merged into a single callback call. (You noticed this one.)
    2. A single message may get split up (at any point) into two separate callback calls.

    Your code must be written to handle both of these cases, otherwise it has a bug.

提交回复
热议问题