首页 > 解决方案 > 如何创建真正无连接的 UdpClient?

问题描述

我的目标是创建 UDP 侦听器来处理传入指定端口的所有数据报,无论其来源如何。然后它用一些消息响应该来源。

public void StartListening(int port = 13000)
{
    ListenerPort = port;
    udpClient = new UdpClient(ListenerPort);

    udpClient.BeginReceive(new AsyncCallback(handleIncomingMessages), null);
}

private void handleIncomingMessages(IAsyncResult ar)
{
    var receivedData = udpClient.EndReceive(ar, ref senderIpEndPoint);
    //[...]
    udpClient.BeginReceive(new AsyncCallback(handleIncomingMessages), null);
}

一切正常,直到我关闭了其中一个“起源”。几秒钟后,我的听众听到了SocketException

现有连接被远程主机强行关闭。

我一直认为 UDP 是一种无连接协议,但 UdpClient 似乎以某种方式跟踪远程主机是否可用。有一些标准的.NET Core 方法可以禁用它吗?

编辑:

这是错误堆栈跟踪:

System.Net.Sockets.SocketException
  HResult=0x80004005
  Message=An existing connection was forcibly closed by the remote host.
  Source=System.Net.Sockets
  StackTrace:
   at System.Net.Sockets.Socket.UpdateStatusAfterSocketErrorAndThrowException(SocketError error, String callerName)
   at System.Net.Sockets.Socket.EndReceiveFrom(IAsyncResult asyncResult, EndPoint& endPoint)
   at System.Net.Sockets.UdpClient.EndReceive(IAsyncResult asyncResult, IPEndPoint& remoteEP)
   at NetworkController.UDP.NetworkManager.handleIncomingMessages(IAsyncResult ar) in [...]
   at System.Net.LazyAsyncResult.Complete(IntPtr userToken)
   at System.Net.ContextAwareResult.CompleteCallback()
   at System.Net.ContextAwareResult.<>c.<Complete>b__15_0(Object s)
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)

标签: c#.net-coreudpclient

解决方案


推荐阅读