1

I'm developing an application that sends a lot of messages by an UDP connection.

Sometimes some packets were lost and after some tests I conclude that the socket was busy.

Thus I put a tiny sleep between calls to sendto API trying to prevent a new send before the last one ends.

It worked, but I want to use a better approach, like treat a signal or something else which point me that the previous send was done.

Is there anything like that?

I'm using C++ language on a Linux environment.

The below code snippet shows what I'm doing:

#define MAX_SIZE 4096
string long_msg = GetLongMessage();

if (!long_msg.empty()) {
  long int to_send = long_msg.size();
  while (to_send) {
    long int ret = sendto(socket_fd,
                          &long_msg[long_msg.size() - to_send], 
                          (to_send > MAX_SIZE ? MAX_SIZE : to_send), 0,
                          reinterpret_cast<struct sockaddr*>(&addr_client),
                          addr_client_len);
    if (ret > 0) {
      to_send -= ret;
      sleep(10);
    } else {
      // Log error
    }
  }
}

Edit: The intent of this question is to know a way to detect if a UDP socket is busy due a previous send call and not discuss TCP vs UDP advantages/disadvantages.

Valmir
  • 401
  • 1
  • 5
  • 14
  • 1
    Packets being lost or received out of order are issues inherent to using UDP. The best your application using UDP can do is to account for these problems however you see fit (i.e. if I miss a packet here, do such and such). If you don't need to use UDP, TCP/sockets are an alternative in which (tl;dr) such issues don't occur. Relying on `sleep` is not a reliable way to attempt to account for the UDP issues. – Chris Sprague Jun 29 '16 at 13:52
  • Packets often get lost on the internet, and UDP is not the proper protocol if you care about whether a packet was delivered or not, or about the order in which they are delivered. – molbdnilo Jun 29 '16 at 14:10
  • Thanks for your comments. I know the benefits of TCP over UDP and maybe I'll change to it in the future, but I asked this question because I'm curious about this scenario: Is there a way to know that the UDP socket is available/not busy before a new send? – Valmir Jun 29 '16 at 14:27
  • @Valmir as far as I know, UDP uses "mailboxes" rather than "sockets" (just a jargon thing), and there is no such way to check the status of the mailbox. Such functionality is already implemented at the transport layer. – Chris Sprague Jun 29 '16 at 15:34
  • @ChrisSprague I understood, I didn't know about that. Thanks again. – Valmir Jun 29 '16 at 16:23

0 Answers0