Note that there are some explanatory texts on larger screens.

plurals
  1. POC# Async UDP listener SocketException
    primarykey
    data
    text
    <p>I have a pretty simple Asynchronous UDP listener, setup as a service, and it's been working quite well for awhile now, but it recently crashed on a SocketException <code>An existing connection was forcibly closed by the remote host</code>. I have three questions:</p> <ol> <li>What's causing this? (I didn't think UDP sockets had a connection)</li> <li>How can I duplicate it, for testing purposes?</li> <li>How can I cleanly handle the exception, so everything will continue to work?</li> </ol> <p>My code looks something like the following:</p> <pre><code>private Socket udpSock; private byte[] buffer; public void Starter(){ //Setup the socket and message buffer udpSock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); udpSock.Bind(new IPEndPoint(IPAddress.Any, 12345)); buffer = new byte[1024]; //Start listening for a new message. EndPoint newClientEP = new IPEndPoint(IPAddress.Any, 0); udpSock.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref newClientEP, DoReceiveFrom, udpSock); } private void DoReceiveFrom(IAsyncResult iar){ try{ //Get the received message. Socket recvSock = (Socket)iar.AsyncState; EndPoint clientEP = new IPEndPoint(IPAddress.Any, 0); int msgLen = recvSock.EndReceiveFrom(iar, ref clientEP); byte[] localMsg = new byte[msgLen]; Array.Copy(buffer, localMsg, msgLen); //Start listening for a new message. EndPoint newClientEP = new IPEndPoint(IPAddress.Any, 0); udpSock.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref newClientEP, DoReceiveFrom, udpSock); //Handle the received message Console.WriteLine("Recieved {0} bytes from {1}:{2}", msgLen, ((IPEndPoint)clientEP).Address, ((IPEndPoint)clientEP).Port); //Do other, more interesting, things with the received message. } catch (ObjectDisposedException){ //expected termination exception on a closed socket. // ...I'm open to suggestions on a better way of doing this. } } </code></pre> <p>The exception is being thrown at the recvSock.EndReceiveFrom() line.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload