2

I try to receive six messages from UDP unicast clients. Receiver looks like:

UdpClient udpclient = new UdpClient();
IPEndPoint localEp = new IPEndPoint(IPAddress.Parse(ClientIP), ClientPort);
udpclient.Client.Bind(localEp);
udpclient.Client.ReceiveTimeout = 10000;
bool isTimeExpired = false;
while (!isTimeExpired)
{
    byte[] buffer;
    try
    {
        buffer = udpclient.Receive(ref localEp);

    }
    catch (SocketException)
    {
        isTimeExpired = true;
        continue;
    }
    // Deserialize
    // ...
}
udpclient.Close();

Program works, but sometimes I don't receive 6 messages (2 or 3). Sender application:

UdpClient client = new UdpClient();

IPEndPoint remoteep = new IPEndPoint(IPAddress.Parse(ClientIP), ClientPort);

// Serialize
// ...

stream.Position = 0;
byte[] data = new Byte[stream.Length];
stream.Read(data, 0, Convert.ToInt32(stream.Length));
client.Send(data, data.Length, remoteep);
stream.Close();
client.Close();

I run 6 instances of sender application at the same machine (and one instance of receiver). I need to receive messages from every sender (six messages total) all the time. Where is my mistake?

Thank you very much!

Akshay Soam
  • 1,580
  • 3
  • 21
  • 39
user3649515
  • 199
  • 7
  • 17

1 Answers1

2

It's UDP. There's no guarantee you'd receive any of the datagrams that were sent. UDP is, by design, unreliable. The "User" in the UDP might as well stand for "Unreliable" instead. :)

FYI: there also is no guarantee that you'll receive only one copy of any given datagram that was sent. There is also no guarantee that the datagrams will arrive in the same order in which they were sent.

If you need that kind of reliability, then you need TCP, not UDP (or you need to do a bunch of extra work to re-invent the TCP wheel).

Peter Duniho
  • 68,759
  • 7
  • 102
  • 136
  • Peter Duniho, I know UDP doesn't guarantee delivery. I thought may be I need to put something like `Thread.Sleep(1000);` somewhere. Because when I run this programs on my PC in most causes I receive all 6 messages. When I run them on my laptop, I don't receive all messages mostly (receive 2 or 3, sometimes 0). However, thank you! – user3649515 Oct 17 '14 at 21:49
  • It may well be that there is something you can do to improve the reliability of your network stack on that computer. But ultimately, your code needs to be resilient enough to deal with missing datagrams. In this respect, the higher failure rate on that computer is probably a _good_ thing, because it gives you a better test environment to make sure you've written the UDP handling correctly. :) – Peter Duniho Oct 17 '14 at 23:23