Hi, does anyone know of a good way of reducing the timeout used for making
TCP connections through the .NET System.Net.Socket class?

I have tried the documented method from MSDN whereby you set a socket's
blocking property to false prior to making a connect attempt and then trap
the generated SocketException which has an error code of 'WSAEWOULDBLOCK'
and then poll the socket to check for the ability to write using Poll.
Using Poll then allows me to specify the time I want to wait for
completion of the connect.

However, there seems to be a bug in the Socket class in that the socket's
Connected property is only set to true in the Socket.Connect method after
the code where it throws the SocketException.

Therefore if you go through this rigmarole you end up with a socket which
*is* connected but has a Connected property which returns false.  There
appears to be no way of setting the Connected property to true - there
aren't even any protected member which would allow derivation of this
class in order to fix the problem.

So, I'm wondering what alternative methods there are.  Any help would be
greatly appreciated.

Thanks
Phil Parker


Here is an example of the code:

public static Socket Connect(IPEndPoint endPoint, int port, int timeoutMs)
{
 Socket socket = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);

 try
 {
  // do not block - do not want to be forced to wait on (too-
long) timeout
  socket.Blocking = false;

  // initiate connection - will cause exception because
we're not blocking
  socket.Connect(endPoint);
 }
 catch(SocketException socketException)
 {
  // check if this exception is for the expected 'Would
Block' error
  if(socketException.ErrorCode != WsaeWouldBlock)
  {
   socket.Close();

   // the error is not 'Would Block', so propogate
the exception
   throw;
  }

  // if we get here, the error is 'Would Block' so just
continue execution
 }

 // wait until connected or we timeout
 int timeoutMicroseconds = timeoutMs * 1000;
 if(socket.Poll(timeoutMicroseconds, SelectMode.SelectWrite) ==
false)
 {
  // timed out
  socket.Close();

  throw new Exception("The host failed to connect");
 }

 // *** AT THIS POINT socket.Connected SHOULD EQUAL TRUE BUT IS
FALSE! ARGH!

 // set socket back to blocking
 socket.Blocking = true;

 return socket;
}

===================================
This list is hosted by DevelopMentor�  http://www.develop.com
Some .NET courses you may be interested in:

NEW! Guerrilla ASP.NET, 17 May 2004, in Los Angeles
http://www.develop.com/courses/gaspdotnetls

View archives and manage your subscription(s) at http://discuss.develop.com

Reply via email to