Will this code make sure I read all I want from a socket?

后端 未结 2 1095
故里飘歌
故里飘歌 2021-01-19 06:44

Doing a Socket.Receive(byte[]) will get the bytes in from the buffer, but if the expected data is fairly large, all of the bytes might not yet be in the buffer, which would

相关标签:
2条回答
  • 2021-01-19 07:12

    No, the code will not ensure that the complete message is received. You should check the number of bytes received and loop until you have received the complete message.

    Keep in mind that you might also start to receive a portion of the next message if multiple messages are being sent sequentially from the client. For example, if your message is 100 bytes, the first call might return 60 bytes and you will the loop around and read again and get 58 bytes, which means that you have now received the 100 bytes of the first message and the first 18 bytes of the next message, so you need to handle this correctly as well.

    Note: You cannot make any assumptions about how the bytes will be split up as you receive them. It is just a stream and the OS will notify you as it starts to receive data, with no concept of message framing, that is all up to you to manage.

    Hope that makes sense.

    0 讨论(0)
  • 2021-01-19 07:22

    No, Receive returns number of received bytes. You should properly handle this.

    var needBytes = message_byte.Length;
    var receivedBytes;
    var totalReceivedBytes = 0;
    do
    {
        receivedBytes = sock.Receive(message_byte, totalReceivedBytes, needBytes, SocketFlags.None);
        needBytes -= receivedBytes;
        totalReceivedBytes += receivedBytes;
    } while (needBytes > 0 && receivedBytes > 0)
    
    0 讨论(0)
提交回复
热议问题