[英]Why doesn't TcpClient.BeginConnect result's AsyncWaitHandle.WaitOne return false if the listening service is down?
I am making a connection to a service i created on another server via: 我通过以下方式连接到我在另一台服务器上创建的服务:
using (var clientSocket = new TcpClient())
{
...
//Connect async
var result = clientSocket.BeginConnect(hostIP, portNumber, null, null);
//Wait for connection up to our timeout
if (!result.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(5)))
{
//This is NEVER run
throw new Exception("Connection timed out.");
}
//It makes it here but shouldn't!
}
If the other server is up but the service that listens on the port is down, this still returns true! 如果其他服务器已启动,但侦听端口的服务已关闭,则仍会返回true! (And if the server is down, it does properly throw the exception)
(如果服务器关闭,它会正确抛出异常)
Why? 为什么?
How do I make it fail if the service is down (and thus nothing's listening on that port)? 如果服务中断(如果没有在该端口上监听),如何使其失败?
Perhaps you could use the newer ConnectAsync
method instead which even allows you to supply a CancellationToken
in case you require your client-connecting task to abort prematurely. 也许您可以使用较新的
ConnectAsync
方法,甚至允许您提供CancellationToken
,以防您需要客户端连接任务过早中止。
using (var clientSocket = new TcpClient())
{
//Connect async and wait for connection up to our timeout
if (!clientSocket.ConnectAsync(hostIP, portNumber).Wait(TimeSpan.FromSeconds(5)))
{
throw new Exception("Connection timed out.");
}
}
It would appear that there's no way to have it fail if there's nothing listening. 如果没有什么可听的话,似乎没有办法让它失败。 Instead, you can use a
ReadTimeout
to handle the error of nothing listening on the other end. 相反,您可以使用
ReadTimeout
来处理另一端没有任何侦听的错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.