1

I'm trying to send an image (called frame) using an UDP socket over ethernet using the standalone ASIO library (C++). I have an infinite loop that runs 30 times per second and, at each iteration, I'd like to send the frame over UDP. Frames are managed as c-style char array (char frame[]).

I read that ASIO supports async operations and I'm trying to use the async_send_to method to send the frame without blocking the caller (in order to not block the camera). Since each frame is around 4 MB, I have to send small packets of 1500 byte (max dimension allowed by UDP is 65537 but the physical ethernet limit is 1500 byte). Thus, at each camera iteration, I have to send more than 3000 packets over UDP.

I read a lot of documentation regarding ASIO and I came up with the following solution (high level pseudo-code):

    asio::io_context io_context;
    while(true){ // camera infinite loop
        auto frame = camera.getFrame(); // byte array

        for(i = 0; i < 3000; i++){
            char packet[1500]; 
            ...
            // fill the packet with (1500 - header) byte of the frame (header to reorder the packet
            ... 
            socket.async_send_to(packet); 
        }

        io_context.run(); // wait async operations to finish
        io_context.reset(); 
    }

I'm not sure if it is an efficient solution and if I used properly the io_context.run() function. I'm concerned for the inner loop, it takes too much time and I'm wondering if anyone knows how I can improve my code.

Thank you in advance

F. DePa
  • 143
  • 1
  • 1
  • 8

1 Answers1

1

io_context.run() blocks the thread until all async handlers are dispatched, you may want to run it in another thread, possibly with a executor_work_guard to prevent it from returning.

However, your approach is flawed. UDP is not suitable for your use case, because it is unreliable and does not guarantee packet ordering. Even if all of the sent packets reach the destination, they receiver may get them out-of-order. Consider using TCP for this.

sparik
  • 1,181
  • 9
  • 16
  • Thanks for the threading suggestion. Regarding the ordering, I think I can handle it adding an header to each packet. The header will contain an index to correctly construct the frame at the receiver side. My problem is how to efficiently send the packet. – F. DePa May 11 '20 at 01:59
  • why not just use tcp? – sparik May 11 '20 at 11:10
  • isn't TCP slower than UDP? – F. DePa May 12 '20 at 05:21
  • 1
    it depends, sometimes it will be faster. moreover, you are going to add a layer on top of udp. tcp is the obvious choice here. – sparik May 12 '20 at 05:37