Reputation: 2575
I have a UdpClient sending small datagrams back and forth to another client. I'm trying to pull one datagram at a time out of the Socket's buffer by using
udpClient.Client.Receive(byte[] buffer, int offset, int size, SocketFlags socketFlags);
and I'm having two problems. The first problem is when receiving, I'm pulling one byte less than is available from the socket and I get a SocketException:
A message sent on a datagram socket was larger than the internal message buffer or some other network limit, or the buffer used to receive a datagram into was smaller than the datagram itself
This is the case when (trying to pull 6 bytes of the available 7):
Client.Available = 7
buffer = byte[1024]
offset = 0
size = 6
socketFlags = SocketFlags.None
The underlying socket buffer size is something big, like 8k. I found that if I set size=Client.Available, I do not get this error. For some reason, it doesn't like that I'm trying to pull only 6 of the 7 bytes out of the socket.
To get around this, I used the overload
udpClient.Client.Receive(byte[] buffer, int offset, int size, SocketFlags socketFlags, out SocketError socketError);
and ignored the "error". This let me receive 6 of the 7 bytes.
However, this gave way to the second problem, which is:
When I pull 6 of the 7 bytes available on the socket, the buffer flushes, and Socket.Available = 0. What baffles me is this code was working maybe 6 months ago, but on a different machine. I've done some reading and I guess the SocketException can be caused by the OS accessing the socket, but I was using Windows 7 64-bit both then and now. Has anyone ever experienced a problem like this, or might have some knowledge to shed light on the subject? Thanks for all your help!
Upvotes: 0
Views: 271
Reputation: 310859
You're supposed to read the whole datagram at once. If you don't, at best the remainder is lost. It's not a byte stream like TCP.
Upvotes: 1