Reputation: 15950
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.
Upvotes: 2
Views: 3079
Reputation: 27363
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.
Upvotes: 2