I implement a simple LAN discovery protocol, so I call UdpClient.Send and then UdpClient.BeginReceive. If more than one response is expected, I call UdpClient.BeginReceive at the end of the callback. Something like that:
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);
My problem is that my main loop calls client.Close while receiving is still client.Close . The receiving completes, and then my next call to BeginReceive raises 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?
source share