Mono Sockets – Connect() ‘ing Forever

100px-Mono_project_logo.svg
In .NET 4.5 on Windows, this code will work as expected with the Connect() Function Timing out if it takes too long.


Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//60 Seconds * 1000 miliseconds
socket.ReceiveTimeout = 60000;
socket.SendTimeout= 60000;

socket.Connect(IpAddress, Port);

However, on Mono 4.2.1 it doesn’t follow the same logic and will continue to wait for the Connect(), even if you set a Timeout.

To fix this use the ASYNC BeginConnect Method, and make your own timer.


var result = socket.BeginConnect(Address, Port, null, null);
//60 Second Wait
bool Success = result.AsyncWaitHandle.WaitOne(60000, true);
if (!Success)
{
socket.Close();
//Correctly Passes the right Exception ID
throw new SocketException((int)SocketError.TimedOut);

}

Comments are closed, but trackbacks and pingbacks are open.