In a project I am working on I had to do NTP time synchronisation on a WindowsCE client. The UdpClient it's Receive() call does not time out so I found this solution on the web:
public class UdpTimeoutClient : UdpClient
{
private class SocketState
{
public Socket Socket;
public byte\[\] Buffer;
public int BytesRead;
public ManualResetEvent WaitHandle;
public SocketState()
{
Socket = null;
Buffer = null;
BytesRead = 0;
WaitHandle = new ManualResetEvent(false);
}
}
private static void ReceiveCallback(IAsyncResult ar)
{
SocketState state = (SocketState)ar.AsyncState;
try
{
state.BytesRead = state.Socket.EndReceive(ar);
}
catch
{
}
state.WaitHandle.Set();
}
public int Receive(ref byte\[\] buffer, int timeout)
{
SocketState state;
AsyncCallback callback;
IAsyncResult result;
state = new SocketState();
state.Socket = Client;
state.Buffer = buffer;
callback = new System.AsyncCallback(UdpTimeoutClient.ReceiveCallback);
result = state.Socket.BeginReceive(state.Buffer, 0, state.Buffer.Length, System.Net.Sockets.SocketFlags.None, callback, state);
if (state.WaitHandle.WaitOne(timeout, false))
{
return state.BytesRead;
}
else
{
return -1;
}
}
}
Can you spot the leak?
We are the all singing, all dancing crap of the world. - Tyler Durden