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;
The code above is what I call to connect to a host, port of a proxy.
The WaitOne
is essentially a timeout. If it returns false, it's timed out.
My question here, is am I calling Close
/Dispose
/GetStream().Close
etc properly on each condition? From what I can tell I should be using EndConnect
here with the connection variable but wherever I try to place it, it gives me a SocketException
saying the target machine refused connection, yet its either not connected anyway or it IS connected already.