c# - 如何创建真正无连接的 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)
解决方案
推荐阅读
- oauth - 如何缓解客户端放弃刷新令牌请求而不是服务器放弃的 OAuth 问题?
- ansible - ansible,带有循环的 jinja 模板,丢失换行符
- r - 重新创建文件扩展名以便在 R 中轻松加载
- node.js - 通过 Dialogflow 实现在 Google Actions 上设置上下文
- java - 在程序处于活动状态时更改 Medusa Gauge 的 maxValue
- javascript - 无法使用前导零 ListJS 对小数进行排序
- javascript - 使用 d3.js 的 svg 视图框:图形上方的空间仍然太大
- javascript - 导入远程主机上的所有模块时的包裹构建问题
- javascript - React.js 使用 axios 发送整数数据但在 Node.js 中获取 [object object]
- django - 在 cmd 行运行时出错