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

后端 未结 2 1177
故里飘歌
故里飘歌 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: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)
    

提交回复
热议问题