I read about the Problem that Socket.Connect might block forever.
I solved this with the following code:
/// <summary>
/// Opens a Tcp client connection
/// </summary>
/// <param name="ip">Server ip address</param>
/// <param name="port">Server port</param>
/// <param name="timeout">Timeout in milliseconds</param>
/// <returns>Returns the Tcp socket</returns>
public static Socket OpenTcpClient(IPAddress ip, int port, int timeout)
{
var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
if (timeout < 0)
{
socket.Connect(new IPEndPoint(ip, port));
}
else
{
var doneEvent = new ManualResetEvent(false);
Exception connectException = null;
var thread = new Thread(() =>
{
try
{
socket.Connect(new IPEndPoint(ip, port));
doneEvent.Set();
}
catch (Exception ex)
{
connectException = ex;
try
{
doneEvent.Set();
}
catch
{}
}
});
thread.Start();
try
{
if (doneEvent.WaitOne(timeout, false))
{
if (connectException != null)
{
throw connectException;
}
}
else
{
throw new TimeoutException();
}
}
finally
{
if (thread.IsAlive)
{
try
{
thread.Abort();
}
catch { }
}
}
}
return socket;
}
Can anyone tell me if this is the right way to do handle this issue?
I mean, it is working, but I’m not verry experianced in aborting threads.