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)