TcpClient tcp = new TcpClient();
bool failed = false;
IAsyncResult connection = tcp.BeginConnect(host, port, null, null);
if (!connection.AsyncWaitHandle.WaitOne(_connectTimeout))
{
failed = true;
if (tcp.Client.Connected)
{
tcp.GetStream().Close();
tcp.Close();
}
}
else
{
if (!tcp.Connected)
{
failed = true;
if (tcp.Client.Connected)
{
tcp.GetStream().Close();
}
tcp.Close();
}
}
return tcp;
上面的代码是我所谓的连接到主机,代理端口的代码。
WaitOne
本质上是超时。如果它返回false,则超时。
我的问题是,我是否在每种条件下正确调用Close
/ Dispose
/ GetStream().Close
等?据我所知,我应该在EndConnect
使用连接变量,但无论我在哪里放置它,它都会给我一个SocketException
说目标机器拒绝连接,但它要么没有连接,要么它已经连接了。
答案 0 :(得分:0)
这解决了我的问题(这是我编辑的另一个解决方案,信用如下):
TcpClient tcp = new TcpClient();
#region Try connect
IAsyncResult ar = tcp.BeginConnect(host, port, (ari) => {
TcpClient tcpi = (TcpClient)ari.AsyncState;
try {
tcpi.EndConnect(ari);
} catch { }
if (tcpi.Connected) {
return; //return IAsyncResult and waitone will be true
}
//otherwise it will close the tcpi and never return, causing the timeout to kickin.
tcpi.Close();
}, tcp);
#endregion
#region If timed out, or not connected return null
if (!ar.AsyncWaitHandle.WaitOne(_connectTimeout, false) || !tcp.Connected) {
return null; //this is my use case, you might want to do something different
}
#endregion
return tcp;
关于链接另一个类似问题的信用:
@JeroenMostert
对类似问题的原始解决方案的信用:
@Adster