views:

163

answers:

1

I use UDP Sokckts in my client application. Here are some code snippets:

SendIP = new IPEndPoint(IPAddress.Parse(IP), port);
ReceiveIP = (EndPoint)(new IPEndPoint(IPAddress.Any, 0));
socket = new Socket(
    AddressFamily.InterNetwork,
    SocketType.Dgram,
    ProtocolType.Udp);
socket.Bind(ReceiveIP);

And to Receive (while(true)):

byte[] data = new byte[BUFFERSIZE];
int receivedDataLength = socket.ReceiveFrom(data, ref ReceiveIP);
string s= Encoding.ASCII.GetString(data, 0, receivedDataLength);

I am doing an infinite while on the receive, there are other things to be done in the while, even if nothing is received..

  • I want to check if there are actually available data then receive else do not wait.. (Note the current receive method waits until the server sends a message)
+1  A: 

You could use socket.Available() to determine if there is any waiting data before calling ReceiveFrom(). Ideally, though, you should consider farming out input handling to other threads using BeginReceiveFrom() and its asynchronous friends.

sblom