0

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?

rfgamaral
  • 15,937
  • 49
  • 156
  • 269

2 Answers2

1

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.

user207421
  • 289,834
  • 37
  • 266
  • 440
-1

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.

Erez Robinson
  • 776
  • 4
  • 9
  • 'Cannot be lost but they can' is just a contradiction in terms. The socket will close when *you* close it, and under no other circumstances. The *connection* will be dropped (reset) but that does not affect the socket. – user207421 May 22 '16 at 02:02
  • It's not, packets can be lost in the IP or Link layer, that's what I meant. Did you downvote me for that? shame. – Erez Robinson May 24 '16 at 18:01
  • Packets can be lost in the lower layers but TDP will retransmit them. Your error about the socket close remains uncorrected, indeed unnoticed. Your links don't have any apparent bearing on the question. – user207421 Jun 07 '16 at 10:35