4

我在服务器端使用 UdpClient 并将数据发送到客户端(多个客户端)。突然,客户端停止侦听 udp 端口​​,并且服务器在调用 endRecieve 或 beginRecieve 时遇到 SocketException。

据我了解,这是因为“ICMP Destination Unreachable”,它只是告诉服务器端口已关闭。没关系,但是 SocketExceptions 都没有告诉我它来自哪个端点。

我如何知道哪个端点已关闭,以便服务器停止向它发送并导致更多 SocketExceptions?

或者有没有办法让 Udpclient 停止抛出这些 SocketExceptions,这样如果客户端在某某秒后没有响应,我可以让客户端超时。

4

1 回答 1

0

我自己也在处理同样的问题,所以我很想看看是否有人提出了更好的解决方案,但现在我有几个想法:

我的套接字周围有一个 comm 包装类(我们称之为AsyncComm),它在构造时从其所有者类传递了一个异常处理程序委托。异常处理程序委托接受异常的参数和对AsyncComm抛出它的实例的引用。然后我把

try
{
   // Do stuff here
{
catch (Exception e)
{
   CallExceptionHandlerDelegate(e, this);
}

在我的每个异步处理程序方法中AsyncComm,他们可以将异常抛出链上。在我的例子中,异常处理程序使用对实例的引用AsyncComm来调用实例中的方法AsyncComm来告诉它重新初始化其套接字。您可以将该行为更改为您需要做的任何事情以停止不断获取SocketExceptions.

关于确定异常来自的终点,我现在唯一的想法是从SocketException.Message字符串的末尾解析终点,但这似乎是一个很大的问题。

更新:这是一个 kludge,但它的工作原理。解析下面的代码,其中一些取自这个问题

private IPEndPoint parseEndPointFromString(string input)
{
    // Matches 1-255.1-255.1-255.1-255:0-65535. I think.
    const string IPPortRegex = @"(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?):(6553[0-5]|655[0-2]\d|65[0-4]\d\d|6[0-4]\d{3}|[1-5]\d{4}|[1-9]\d{0,3}|0)";

    Match match = Regex.Match(input, IPPortRegex);

    if (match.Success)
    {
        string IPPortString = match.Value;

        string[] ep = IPPortString.Split(':');
        if (ep.Length != 2) throw new FormatException("Invalid endpoint format");
        IPAddress ip;
        if (!IPAddress.TryParse(ep[0], out ip))
        {
            throw new FormatException("Invalid IP address");
        }
        int port;
        if (!int.TryParse(ep[1], out port))
        {
            throw new FormatException("Invalid port");
        }
        return new IPEndPoint(ip, port);
    }
    else
    {
        throw new FormatException("Invalid input string, regex could not find an IP:Port string.");
    }
}
于 2011-06-30T14:46:10.160 回答