gpt4 book ai didi

C# 异步 UDP 监听器 SocketException

转载 作者:太空狗 更新时间:2023-10-29 18:12:37 26 4
gpt4 key购买 nike

我有一个非常简单的异步 UDP 监听器,设置为服务,它现在运行良好已有一段时间,但最近因 SocketException 而崩溃 现有连接被远程主机强行关闭。我有三个问题:

  1. 这是什么原因造成的? (我没想到 UDP 套接字有连接)
  2. 为了测试目的,我如何复制它?
  3. 我怎样才能干净利落地处理异常,让一切继续正常工作?

我的代码如下所示:

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() 行抛出异常。

最佳答案

来自 this forum thread ,似乎UDP套接字也在接收ICMP消息并在接收时抛出异常。也许这对于低级状态更新非常有用,但我发现它很烦人。

首先定义魔数(Magic Number)

public const int SIO_UDP_CONNRESET = -1744830452;

然后设置低级 io 控件忽略这些消息:

var client = new UdpClient(endpoint);
client.Client.IOControl(
(IOControlCode)SIO_UDP_CONNRESET,
new byte[] { 0, 0, 0, 0 },
null
);

关于C# 异步 UDP 监听器 SocketException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5199026/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com