C# Socket BeginReceive / EndReceive capturing multiple messages

前端 未结 3 600
野的像风
野的像风 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).

提交回复
热议问题