2015-11-06 57 views
0

我的程序要求我繼續寫入,同時還需要能夠接收傳入數據。BOOST ASIO。當我的程序繼續發送數據時,異步接收不起作用

這是我試過了。我試圖把async_receive放在不斷接收數據的單獨線程中。此外,我添加無限while循環來保持發送數據。但是,我無法收到任何東西。

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(); };的receive函數工作正常。

在此先感謝。

+0

'async_receive_from'函數會立即返回,所以'receiveThread'是非常短暫的。如果操作在註釋while-forever循環時完成,那麼'io_service'不會在別處運行,因此'async_recieve_from'操作不會完成。考慮閱讀[this](http://stackoverflow.com/a/15575732/1053968)回答以更好地理解操作和'io_service'。 –

回答

0

你的UDPAsyncServer包含一個無限循環(while(1)),所以它永遠不會返回。所以沒有其他事情發生,你的程序掛起。評論循環避免了掛起。