1

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.

1

3 Answers 3

1

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);
Sign up to request clarification or add additional context in comments.

2 Comments

Don't run away from threads, as you'll soon or later bump into it since you are doing stuff asynchronously.
This is for a status page, it checks a few TCP ports to see if they're alive and doesn't ever do anything with them. I think in this scenario running away from threads is the right thing to do.
0

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

1 Comment

I had already tried that. I added that to my original question as well. Thanks.
0

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()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.