Reputation: 1148
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
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
Reputation: 19986
To fine control your timeout, do this:
Application.DoEvents()
Thread.Sleep()
for desired timeout interval. Or use some other method to make the time passSocket.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
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