Tengo un oyente UDP Asincrónico bastante simple, configurado como un servicio, y ha estado funcionando bastante bien por un tiempo, pero recientemente se colgó en una SocketException An existing connection was forcibly closed by the remote host
. Tengo tres preguntas:C# escucha UDP Async SocketException
- ¿Qué está causando esto? (No creo que los sockets UDP tengan una conexión)
- ¿Cómo puedo duplicarlo, para realizar pruebas?
- ¿Cómo puedo manejar limpiamente la excepción, para que todo continúe funcionando?
Mi código es algo como lo siguiente:
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.
}
}
La excepción está siendo lanzado en la línea de recvSock.EndReceiveFrom().
¡Gran hombre! Hola, tuve el mismo problema de recibir mensajes ICMP y arrojar excepciones cuando se reciben. ¡Lo cual se resuelve con tu truco de codificación! – Kevan
@Kyle, ¡finalmente llegué a probar esto por completo! Parecería que esta era la causa real de la excepción. Como referencia, terminé usando tanto tu respuesta como la de Jim, de modo que incluso si hay una excepción, el oyente se reinicia. – chezy525
Enlace roto. Esta respuesta se debe cambiar para actualizar el enlace o incluir la información a la que apunta el enlace. –