How to configure socket connect timeout
I found this. Simpler than the accepted answer, and works with .NET Framework v2
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
// Connect using a timeout (5 seconds)
IAsyncResult result = socket.BeginConnect( sIP, iPort, null, null );
bool success = result.AsyncWaitHandle.WaitOne( 5000, true );
if ( socket.Connected )
{
socket.EndConnect( result );
}
else
{
// NOTE, MUST CLOSE THE SOCKET
socket.Close();
throw new ApplicationException("Failed to connect server.");
}
//...
My take:
public static class SocketExtensions
{
/// <summary>
/// Connects the specified socket.
/// </summary>
/// <param name="socket">The socket.</param>
/// <param name="endpoint">The IP endpoint.</param>
/// <param name="timeout">The timeout.</param>
public static void Connect(this Socket socket, EndPoint endpoint, TimeSpan timeout)
{
var result = socket.BeginConnect(endpoint, null, null);
bool success = result.AsyncWaitHandle.WaitOne(timeout, true);
if (success)
{
socket.EndConnect(result);
}
else
{
socket.Close();
throw new SocketException(10060); // Connection timed out.
}
}
}