Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

sockets

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 give me an only partially filled byte array. Will this code ensure that I read in all that I want?

sock.Receive(message_byte, message_byte.Length, SocketFlags.None);

where message_byte has already been declared as the exact size of the data I'm expecting. Am I going about this in the right way? Nothing this handles would be larger than ~10 megs, so it's unlikely I would have an OutOfMemoryException when declaring the byte array.

like image 747
cost Avatar asked Dec 16 '22 10:12

cost


2 Answers

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)
like image 188
hazzik Avatar answered Jan 12 '23 19:01

hazzik


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.

like image 42
Chris Taylor Avatar answered Jan 12 '23 21:01

Chris Taylor