1

I have this piece of code to send a command through UdpClient and then wait for a response:

cameraListener = new UdpClient(52381);      
cameraSender = new UdpClient();
cameraSender.Connect(endPoint);  

int dataSent = await cameraSender.SendAsync(command, command.Length);
UdpReceiveResult result = await cameraListener.ReceiveAsync();

Note: "endPoint" is just a normal IPAddress:port endpoint.

What would happen if the Camera is offline?

Since it is UDP, the SendAsync will send the data correctly but the ReceiveAsync will wait for a response forever. And if those two lines of code (the SendAsync and the ReceiveAsync) executes periodically, will infinite ReceiveAsync wait for a response forever until the system would crash?

Or will they terminate or be terminated by OS at some time? Is it essential to implement a Timer to manually "kill" the UDP socket to terminate the eternal waits?

Liam
  • 27,717
  • 28
  • 128
  • 190
MorgoZ
  • 2,012
  • 5
  • 27
  • 54

1 Answers1

4

UDP messages can get lost. This means that your receive can indeed wait forever if the other party does not retry its message. You need a timeout.

Even worse, if you run this code multiple times (with the intention of sending multiple times) you can receive a message that was meant for the other send because with concurrent reads on the same socket it is undefined what read gets what data.

If you just queue up more and more reads without timeout you'll exhaust some resource sooner or later. Don't do that.

Probably, you should have a receive loop that just receives everything it gets and processes it.

Sending can be independent from that.

Even better, use a reliable transport like TCP.

usr
  • 168,620
  • 35
  • 240
  • 369
  • Thanks, it is just that i don´t understand why, in a so potentially harmfull situation, the ReceiveAsync method does not internally implement a timeout and it must be implemented manually. But thanks for your answer, it´s clear that a timeout is obligatory. – MorgoZ Jun 30 '14 at 14:51
  • 1
    I don't understand it either. AFAIK async socket IO on Windows does not support timeouts. Unfathomable to me. – usr Jun 30 '14 at 14:52
  • Others might want to check this soln. too: http://stackoverflow.com/questions/12638104/await-udpclient-receiveasync-with-timeout – Vaibhav Nov 02 '15 at 15:40