Connect a socket with timeout

  • Thread starter Thread starter Mike Schilling
  • Start date Start date
M

Mike Schilling

How does one put a timeout on an attempt to connect a socket? There's no
timeout parameter to Socket.Connect(), and while there are socket options
for send and receive timeouts, there is none for connect timeout.
 
Mike,

In order to do this, you will have to time the asynchronous event.
Basically, make a call to BeginConnect, and start a timer at the same time,
with an interval of your timeout.

In the timer function, set a flag indicating if the timer has fired.

Then, in the callback for the BeginConnect method, you check the flag.
If it is set, then you timed out, if not, then you haven't timed out.

You can then elaborate, by creating an Event that is set when the
timeout occurs, or the connection is created. Then, you have your thread
wait on both of those events. Depending on the event fired, you would then
know if there is a timeout, or if the connection succeeded.

Hope this helps.
 
Nicholas Paldino said:
Mike,

In order to do this, you will have to time the asynchronous event.
Basically, make a call to BeginConnect, and start a timer at the same
time, with an interval of your timeout.

In the timer function, set a flag indicating if the timer has fired.

Then, in the callback for the BeginConnect method, you check the flag.
If it is set, then you timed out, if not, then you haven't timed out.

I thought about something like that, but couldn't find a way to abort the
connection attempt if the timer fires and it's still pending. EndConnect is
documented as synchronously completing the connection, and it's not clear
from the docs what Close or Shutdown would do.
 
Hi Mike,

The Close method will release all the resource on the Socket. Shutdown
method will disable the socket from sending and receiving. So, I suggest
you call Close method on the Socket to cancel connecting.

Kevin Yu
=======
"This posting is provided "AS IS" with no warranties, and confers no
rights."
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top