我正在编写一个 ServerLocator,它基本上广播一个端口以查找将响应 IPEndPoint 的服务器,如果在当前 IPHost 上找不到任何内容,我需要搜索能够超时,然后继续下一个。
现在我正在做这样的事情(我已经删除了这段代码的某些部分,因此它只包含显示我的问题所需的内容。这里还有一些客户端绑定(bind))
string serverIp = string.Empty;
while(string.isNullOrEmpty(serverIp))
{
foreach (IPAddress adress in ipHosts.AddressList)
{
using(Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)
{
try
{
client.ReceiveFrom(buffer, ref tempRemoteEP);
//Get server IP
serverIp = tempRemoteEP.ToString().Split(":".ToCharArray(), 2)[0];
break;
}
catch(SocketException e)
{
// We expect connection attempt to time out if we cant find any server on this port and nic. Just continue with the next
if (e.SocketErrorCode == SocketError.TimedOut)
{
continue;
}
}
}
}
}
除控制台收到垃圾邮件外,这按预期工作:
A first chance exception of type 'System.Net.Sockets.SocketException' occurred in System.dll
有没有一种好的方法可以在不向控制台发送垃圾邮件的情况下处理这样的异常?或者我可以用其他方式处理这个问题以避免超时异常的需要吗?
谢谢。
最佳答案
如果程序继续运行,真的不需要担心这个,程序中会发送很多这样的异常。参见 this article有关“首次异常(exception)”的更多信息。
同时检查 this link查看如何配置 Visual Studio 如何处理异常。如果您配置这些,您可以中断(而不是继续)异常并查看到底发生了什么。但是,请注意隐藏异常似乎在调试中不起作用,请参阅 here或 here但正如@Cipi 指出的那样,它不应该在 Release 中可见。
关于c# - 在没有垃圾邮件控制台的情况下处理超时的 Socket.ReceiveFrom,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4861565/