首页 文章

如何确定哪个EndPoint导致SocketException,错误代码为10054? (“现有连接被远程主机强行关闭 . ”)

提问于
浏览
2

总结一下我的情况,我正在编写一个服务器程序,打开一个UDP套接字,任意数量的客户端都可以与之通信 . 我使用类似于以下代码接收UDP数据包:

EndPoint sender = new IPEndPoint(IPAddress.Any, 0);
try
{
    count = socket.ReceiveFrom(buf, ref sender); // 'count' and 'buf' are defined elsewhere
    // If an exception isn't thrown, 'sender' will now contain the EndPoint of the client that sent the packet.
}
catch(SocketException e)
{
    if(e.ErrorCode == 10054)
    {
        // How do I get the EndPoint that caused the error?
        // The 'sender' variable above does not contain the EndPoint.
    }
}

当我的服务器将数据包发送到已关闭其自己的套接字的客户端时,我收到错误代码10054(“现有连接被远程主机强行关闭”) . 我想停止向该客户端发送数据包,以便SocketExceptions停止抛出,这严重损害了我的服务器性能 .

但我的问题是我不知道如何获得强行关闭的特定客户端的EndPoint . (上面的'sender'变量在抛出异常之前没有设置为有用的东西 . )如何找到EndPoint?

一个不太理想但仍然可行的解决方案是简单地禁止抛出SocketException .

有任何想法吗?

谢谢!

1 回答

  • 2

    我想我有个主意 . 您应该创建并维护一个客户列表,这个列表将包含它们的所有 endpoints (以及您可能需要的其他有用信息) .

    然后数据传输将发生在"connected"客户端,而所有其他的"unknown"计算机通常会尝试"connect"给你,尽管 IPAddress.Any .

相关问题