Socket.Available and UDP datagrams

C

Claire

I'm implementing a UDP server socket from the system.net.sockets.socket
class. (no, I don't want to use the udpclient class)
I'm polling the socket in a thread, testing the socket.available property on
each pass.
With datagrams, does socket.available only advertise when there are complete
packets in its buffers?
What i mean to say is that if socket.Available > 0 then there will be at
least 1 whole datagram ready to be read? So, if less than a full datagram
arrived, socket.available would return zero?
I've already noticed that if socket.Available is greater than the size of a
single datagram Socket.Read method returns a single datagram leaving the
remainder of the bytes in a buffer ready to be collected with subsequent
calls to socket.read (even if you ask for the whole buffer)
Hoping that someone else will have studied the socket classes' behaviour.
thanks

Example server UDP dotnet socket code
myServerSocket = new Socket(System.Net.Sockets.AddressFamily.InterNetwork,
System.Net.Sockets.SocketType.Dgram,
System.Net.Sockets.ProtocolType.Udp);
myServerEndpoint = new System.Net.IPEndPoint(System.Net.IPAddress.Any,
12345);
myServerSocket.Bind(myServerEndpoint);
while(Condition)
{
Available = myServerSocket.Available;
if (Available > 0)
{
foobar();
}
Thread.Sleep(sleeptime);
}
 
K

Kevin Yu [MSFT]

Hi Claire,

First of all, I would like to confirm my understanding of your issue. From
your description, I understand that you need to know if socket.available
only advertise when there are complete packets in its buffers. If there is
any misunderstanding, please feel free to let me know.

As far as I know, it has to return the size of the first message when a
complete message is available in buffer. According to MSDN, if you are
using a message-oriented socket type such as Dgram, the available data is
the first message in that buffer. If no data is queued in the network
buffer, Available returns 0.

So there are complete messages in buffer, it returns the size of the first
one. Or it returns 0.

HTH.

Kevin Yu
=======
"This posting is provided "AS IS" with no warranties, and confers no
rights."
 
W

William Stacey [MVP]

Unless you have some need not given here, polling like this is very
inefficient for a service. Instead, block on Receive(). The thread will
wait/block until a whole datagram arrives.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top