BOOST ASIO。当我的程序继续发送数据时,异步接收不起作用

时间:2015-11-06 03:17:56

标签: c++ boost boost-asio

我的程序要求我继续写作,同时还需要能够接收传入的数据。

这就是我尝试过的。我试图将async_receive放在不断接收数据的单独线程中。此外,我添加无限循环以继续发送数据。但是,我无法收到任何东西。

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];
};

如果我注释掉while (1) { sendingData(); };接收功能正常工作。

提前致谢。

1 个答案:

答案 0 :(得分:0)

你的UDPAsyncServer包含一个无限循环(while(1))所以它永远不会返回。所以没有其他事情发生,你的程序挂起了。注释循环可以避免挂起。