我有一个非常简单的异步UDP侦听器,作为服务设置,它现在一直工作得很好,但它最近在SocketException An existing connection was forcibly closed by the remote host
上崩溃。我有三个问题:C#异步UDP侦听器SocketException
- 这是什么原因造成的? (我不认为UDP套接字有连接)
- 如何复制它,出于测试目的?
- 我该如何干净地处理异常,所以一切都会继续工作?
我的代码看起来像下面这样:
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.
}
}
唯一的例外是在recvSock.EndReceiveFrom()行被抛出。
伟人!嗨同样的问题接收ICMP消息,并在收到时抛出异常。你的编码技巧解决了这个问题! – Kevan 2013-03-08 13:02:23
@凯尔,我终于完全测试了这个!这似乎是这个例外的真正根源。作为参考,我最终使用了答案和Jim,这样即使有异常,监听器也会重新启动。 – chezy525 2013-07-30 21:12:54
Broken Link。此答案应更改为更新链接或包含链接指向的信息。 – 2014-03-02 02:23:07