Question

Simply put, is it possible to reuse a socket after a TimedOut exception has been caught? How can I do it?

Long story:

I have 2 threads, both using the same socket. One is sending packets (let's call it thread A) to a remote server while the other (thread B) is listening for confirmation packets of those sent packets. Thread A will pause (with Monitor.Wait) when some condition is met, waiting for a Monitor.Pulse to continue. When thread B receives a packet, it calls Monitor.Pulse and thread A continues to do it's thing...

The problem is that packets can be lost and thread B will wait indefinitely for a packet that won't receive while thread A is waiting for a pulse. The whole program will "block". My first thought was to set a receive timeout and catch the associated exception. When that happens, I call Monitor.Pulse and thread A can continue while thread B will keep waiting for another packet.

But this doesn't work. When the exception is caught, the socket will close and the app will crash when thread A tries to send a new packet, since they are using the same socket.

How can I prevent this behavior?

Was it helpful?

Solution

TCP Packets cannot be lost (they can but that's on a whole different layer).
If there is a communication error the socket will close.
However if you're using UDP Communications and you've selected a receive timeout, there is no reason you shouldn't be able to try again.

Check This out.
And Read the remarks here.

OTHER TIPS

The problem is that packets can be lost

No they can't. TCP does not lose packets. If you are losing packets you have a bug in your code, or the sender isn't sending them. No problem here yet.

When the exception is caught, the socket will close

No it won't. It will only close when you close it.

and the app will crash when thread A tries to send a new packet, since they are using the same socket.

Only if you closed the socket when you caught the timeout exception. So don't do that.

How can I prevent this behavior?

Don't close the socket when you catch the timeout exception.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top