我自己也在处理同样的问题,所以我很想看看是否有人提出了更好的解决方案,但现在我有几个想法:
我的套接字周围有一个 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.");
}
}