I'm implementing a simple local-network discovery protocol, so I call UdpClient.Send and then UdpClient.BeginReceive. In case more than one response is pending, I call UdpClient.BeginReceive at the end of the callback. Something like this:
UdpClient client = new UdpClient(AddressFamily.InterNetwork);
client.EnableBroadcast = true;
client.Send(request, request.Length, broadcastEndPoint);
client.BeginReceive(Callback, client);
...and then in Callback
:
void Callback(IAsyncResult ar)
{
UdpClient client = (UdpClient)ar.AsyncState;
IPEndPoint remoteEndPoint = null;
byte[] response = client.EndReceive(ar, ref remoteEndPoint);
// Do something with response
client.BeginReceive(Callback, client);
}
My problem is that my main loop calls client.Close
while there's still a receive pending. The receive completes, and then my next call to BeginReceive throws an exception: System.Net.Sockets.SocketException: An existing connection was forcibly closed by the remote host
Why doesn't UdpClient have a CancelReceive method? What can I do instead?