How to timeout a socket connection attempt

m_elias

Member
Joined
Jan 3, 2012
Messages
11
Location
Canada
Programming Experience
1-3
So after several days of searching, reading and testing I figure it's time I ask for some help. I'm writing a proof of concept windows forms application in VB2010 that involves trying to maintain a good socket connection to an ethernet serial server in conditions when the wireless connection will be dropping and reconnecting. It seems I'm having the most trouble with reducing the socket's connection attempt timeout. What I mean is the amount of time it takes for sckt1.BeginConnect to timeout when the server is not reachable so that it can re-attempt the connection. Currently I'm using a variable to track how long it's been since it last received data, if that exceeds my limit (2 secs) then I want it to rapidly attempt to reconnect. Sometimes the connection goes down for only a couple seconds (according to pings), but the socket does not resume receiving data automatically so I close the existing socket and start trying to reopen it again. Currently I am using the following to shorten the built in 20-30 secs connection attempt timeout and I suspect that the socket connect attempt is still timing out in the background when I try reconnecting again.

VB.NET:
do
     sckt1 = New Net.Sockets.Socket(Net.Sockets.AddressFamily.InterNetwork, Net.Sockets.SocketType.Stream, Net.Sockets.ProtocolType.Tcp)
     sckt1.LingerState = New Net.Sockets.LingerOption(True, 0)
     Dim result = sckt1.BeginConnect(Sckt1ServerIP, Sckt1ServerPort, Nothing, Nothing)
     Dim success = result.AsyncWaitHandle.WaitOne(1000, True)
     If Not sckt1.Connected Then
         sckt1.close
     else
         'collect data and do stuff
     end if
     '2 sec delay goes here
loop

That is the general idea of it. It is actually all in a Try/Catch also to catch Exceptions but it is not throwing any exceptions at this time. If I let it loop often enough it seems as though the original failed connection attempt expires and then it will connect again. If the connection is good and data is flowing smoothing, and I close the connection then it is able to reopen it very quickly. The problem seems to be in the connection attempt timeout. Should I spawn a new thread for each connection attempt? Any suggestions how to do that without causing problems?

Thanks.

Maybe I should start a ping and only attempt to connect if the server responds.
 
Last edited:
Back
Top