C# Socket BeginReceive / EndReceive capturing multiple messages

前端 未结 3 599
野的像风
野的像风 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:49

    TCP sockets don't always send data right away -- in order to minimize network traffic, TCP/IP implementations will often buffer the data for a bit and send it when it sees there's a lull (or when the buffer's full).

    If you want to ensure that the messages are processed one by one, you'll need to either set socket.NoDelay = true (which might not help much, since data received may still be bunched up together in the receive buffer), implement some protocol to separate messages in the stream (like prefixing each message with its length, or perhaps using CR/LF to separate them), or use a message-oriented protocol like SCTP (which might not be supported without additional software) or UDP (if you can deal with losing messages).

    0 讨论(0)
  • There is no need to abandon Tcp because it is stream oriented.

    You can fix the problems that you are having by implementing message framing.

    See

    http://blogs.msdn.com/malarch/archive/2006/06/26/647993.aspx

    also:

    http://nitoprograms.blogspot.com/2009/04/message-framing.html

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题