c++ - UDP Boost ASIO 异步客户端挂起

标签 c++ boost udp boost-asio udpclient

我正在尝试使用 boost asio 制作一个玩具异步回显客户端。由于某种原因,它在等待 send_=true 时但在收到回显之前在第二个请求/回复周期被阻止(不会导致服务器崩溃)。

/*
UDP asynchronous clint using boost asio library
 */
#include <cstdlib>
#include <iostream>
#include <algorithm>

#include <boost/array.hpp>
#include <boost/asio.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/thread.hpp>
#include <boost/bind.hpp>
#include <boost/chrono/duration.hpp>

#include "dbook/test/tools.hpp"

using boost::asio::ip::udp;

const size_t N_MESSAGES = 1024;

class udp_client {
public:
  udp_client(const std::string& host,const std::string& service)
    :io_service_(),
     socket_(io_service_),
     replied_(false),
     sent_(false)
  {
    socket_.open(boost::asio::ip::udp::v4());
    udp::resolver resolver(io_service_);
    udp::resolver::query query(udp::v4(), host,  service);
    endpoint_ = *resolver.resolve(query);

  }
  ~udp_client() {
    socket_.close();
  }

  bool sent() {
    return sent_;
  }

  void send(const int r) {
    replied_ = false;
    sent_ = false;

    memcpy(&send_buf_[0],&r,sizeof(int));
    std::cout << "prepare sending" << std::endl;

    socket_.async_send_to(boost::asio::buffer(send_buf_), endpoint_,
              boost::bind(&udp_client::handle_send, this,
                      boost::asio::placeholders::error,
                      boost::asio::placeholders::bytes_transferred));
    io_service_.run_one();

    std::cout << "after run_one" << std::endl;

  }

  bool replied() {
    return replied_;
  }

  int reply() {
    return *reinterpret_cast<int*>(&recv_buf_[0]);
  }

private:
  void handle_send(const boost::system::error_code& error,
           std::size_t size)
  {
    if (error) {
      //missing error propagation to main thread
      std::cerr << "ERROR: Client error while sending (error code = " << error << "): "  << std::endl;
      std::cerr << "ERROR: Recovering..." << std::endl;

    } else {
      sent_ = true;
      std::cout << "sent" << std::endl;
      socket_.async_receive_from(boost::asio::buffer(recv_buf_), endpoint_,
                 boost::bind(&udp_client::handle_receive, this,
                         boost::asio::placeholders::error,
                         boost::asio::placeholders::bytes_transferred));
      io_service_.run_one();


    }
  }

  void handle_receive(const boost::system::error_code& error,
              std::size_t size) {
    if (error) {
      //missing error propagation to main thread
      std::cerr << "ERROR: Client error while receiving (error code = " << error << ")" << std::endl;
      std::cerr << "ERROR: Recovering..." << std::endl;

    } else {
      std::cout << "received" << std::endl;

      replied_ = true;
    }
  }


private:
  boost::asio::io_service io_service_;
  udp::socket socket_;
  udp::endpoint endpoint_;
  volatile bool replied_;
  volatile bool sent_;
  volatile int reply_;
  boost::array<char, sizeof(int)> send_buf_;
  boost::array<char, sizeof(int)> recv_buf_;

};

int main(int argc, char* argv[]) {

  if (argc != 3) {
    std::cerr << "Usage: udp_echo_client <host> <port>" << std::endl;
    return 1;
  }

  try {
    udp_client c(argv[1],argv[2]);

    for(size_t i=0; i != N_MESSAGES; ++i) {
      int r = rand();
      c.send(r);

      //here we could put a tiemeout
      while (!c.sent()) {
    boost::this_thread::sleep(boost::posix_time::milliseconds(10)); 
      }

      //here we could put a tiemeout
      while (!c.replied()) {
    boost::this_thread::sleep(boost::posix_time::milliseconds(10)); 
      }
      int resp = c.reply();

      std::cout << "sent= " << r << ", received= " << resp << std::endl;
      assert(r == resp);
    }

  } catch (std::exception& e) {
    std::cerr << "ERROR: " << e.what() << std::endl;
  }

  return 0;
}

我得到的日志是:

$ ./bin/udp_echo_client localhost 11111
prepare sending
sent
received
after run_one
sent= 16807, received= 16807
prepare sending
after run_one

我想这是我对如何使用 boost asio 缺乏了解。因此,如果有人能解释为什么程序会这样运行,我将不胜感激:)

最佳答案

按照建议宣传我的评论:

通常,您需要连续轮询io_service(或者更恰本地说,只需调用io_service::run。在这种特殊情况下,您需要调用io_service::reset()io_service::run_one() 完成后。

关于c++ - UDP Boost ASIO 异步客户端挂起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12642643/

相关文章:

c++ - 延迟 MSAA 伪造

c++ - int main() 和 void main() 哪个更快?

枚举类型的 C++ 静态成员变量无法编译

c++ - Operator[][] 重载 - 改变值

c++ - boost 日志 : how to filter by current thread id

c++ - 迭代器后继

javascript - 事件页面卸载后,没有在 Chrome 上获取 UDP 套接字的 onReceive 回调

c++ - C++条件变量中的boost同步队列不会通知其他线程上的等待类方法

c# - 不确定将 EndPoint 传递给 Socket.ReceiveFrom()

python - 从 UDP 套接字读取所有数据