How to timeout a TCP connection?

J

John

I would like to be able to timeout a TCP read opeartion. Apparently
TCPClient does not support ReceiveTimeout in Compact Framework and the
BeginReceive method is not supported either. Is there a way to implement
a receive timeout in Compact Framework? Thanks.

John
P.S.
Don't reply to the return address.
 
P

Paul G. Tobey [eMVP]

What do you want to do if the time-out occurs? If you're going to decide
that the socket is broken and close it, you can have a second thread do a
wait on an event or something of that sort, which the read thread will set
when it's gotten back from the read. If the event fires, the time-out
thread does nothing. If the wait times out before the event fires, the
time-out thread calls Close() on the socket, causing an error to be
returned/thrown to the read thread.

The read thread would look something like this:

Start_TimeOutThread( timeout, event );
try
{
socket.Read();
event.Set();
}
catch (IOException)
{
// Handle whatever happened, realizing that it might be caused by the
timeout thread
// closing the socket out from under us.
}

The time-out thread might look something like this:

if ( event.Wait( timeout ) == timeout )
{
socket.Close();
}

Paul T.
 
J

John

Paul,

Thanks. I was not sure if another thread could close a socket opened on
another thread.

John
 
P

Paul G. Tobey [eMVP]

I haven't done it in .NET CF, but it certainly works in another thread
running in the same process from native code. I can't think of any good
reason why it wouldn't work.

Paul T.
 

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

Top