0

My program require me to keep writing while also need to be able to receive incoming data.

This is what I tried. I tried to put async_receive in separate thread that constantly receiving data. Also I add infinite while loop to keep sending data. However, I am not be able to receive anything.

class UDPAsyncServer {
public:
  UDPAsyncServer(asio::io_service& service, 
                 unsigned short port) 
     : socket(service, 
          asio::ip::udp::endpoint(asio::ip::udp::v4(), port))
  {  
     boost::thread receiveThread(boost::bind(&UDPAsyncServer::waitForReceive, this));
     receiveThread.join();
     while(1) {
         sendingData();
     }
  }

  void waitForReceive() {
    socket.async_receive_from(asio::buffer(buffer, MAXBUF),
          remote_peer,
          [this] (const sys::error_code& ec,
                  size_t sz) {
            const char *msg = "hello from server";
            std::cout << "Received: [" << buffer << "] "
                      << remote_peer << '\n';
            waitForReceive();

            socket.async_send_to(
                asio::buffer(msg, strlen(msg)),
                remote_peer,
                [this](const sys::error_code& ec,
                       size_t sz) {});
          });
  }

  void sendingData() {

          std::cout << "Sending" << "\n";
          //In this code, I will check the data need to be send,
          //If exists, call async_send
          boost::this_thread::sleep(boost::posix_time::seconds(2));
      }

private:
  asio::ip::udp::socket socket;
  asio::ip::udp::endpoint remote_peer;
  char buffer[MAXBUF];
};

If I commented out the while (1) { sendingData(); }; the receive function working fine.

Thanks in advance.

Tanner Sansbury
  • 51,153
  • 9
  • 112
  • 169
Adrian
  • 273
  • 1
  • 4
  • 14
  • The `async_receive_from` function will immediately return, so the `receiveThread` is very short-lived. If the operation completes when commenting out the while-forever loop, then the `io_service` is not being ran elsewhere and hence the `async_recieve_from` operation will not complete. Consider reading [this](http://stackoverflow.com/a/15575732/1053968) answer to get a better understanding of operations and `io_service`. – Tanner Sansbury Nov 06 '15 at 15:24

1 Answers1

0

Your UDPAsyncServer contains an infinite loop ( while(1) ) so it never returns. So nothing else happens, your program hangs. Commenting out the loop avoids the hang.

ravenspoint
  • 19,093
  • 6
  • 57
  • 103