Steve Evans
Steve Evans

Reputation: 1148

Timeout on TCP Connection Attempt

In C# I'm trying to test connectivity to a port like this:

Socket socket = new Socket(AddressFamily.InterNetwork,
                    SocketType.Stream,
                    ProtocolType.Tcp);

socket.Connect(telco.Address, telco.Port);

It works great when the port is available. However when the port is not available (e.g. google.com on TCP/81) it takes a long time (~60 seconds) for it to timeout. This is for a status page so I want to fail relatively quickly.

I tried to set socket.SendTimeout and socket.RecieveTimeout to 5000ms (5 seconds) but that appears to have no effect.

Upvotes: 1

Views: 2505

Answers (3)

Steve Evans
Steve Evans

Reputation: 1148

I ended up going with code similar to this to maintain simplicity:

Socket socket = new Socket(AddressFamily.InterNetwork,
                    SocketType.Stream,
                    ProtocolType.Tcp);

IAsyncResult result = socket.BeginConnect(telco.Address, telco.Port, null, null);

bool connectionSuccess = result.AsyncWaitHandle.WaitOne(5000, true);

Upvotes: 1

Daniel Mošmondor
Daniel Mošmondor

Reputation: 19986

To fine control your timeout, do this:

  • fire up one thread with the code above
  • after thread is fired and socket connection is attempted, do what you need (i.e. something you have a little time for, at least Application.DoEvents()
  • Thread.Sleep() for desired timeout interval. Or use some other method to make the time pass
  • check if the connection is open from your main thread. You can do this by observing some state variable that you'll set after successful connection is made.
  • if so, use the connection. If not, use Socket.Close() on your waiting socket to break the connection attempt.

Yes, you'll get the exception in the thread that tries to connect, but you can safely gobble it and assume that everything is OK.

http://msdn.microsoft.com/en-us/library/wahsac9k(v=VS.80).aspx Socket.Close()

Upvotes: 0

MandoMando
MandoMando

Reputation: 5515

think you're looking for socket.ReceiveTimeout();

or use beginConnect() and use a sync tool such AutoResetEvent to catch the time out.

see this post: How to configure socket connect timeout

Upvotes: 0

Related Questions