c++ - asio "std::error_code"没有在 eclipse 中解决?

标签 c++ eclipse c++11 boost-asio

我完全是 ASIO c++ 套接字库的新手。设法使用“asio nonboost”和 openssl 库在 eclipse 中进行设置。 现在我卡在“std::error_code”未解决。

请帮忙,我已经花了很多时间在这上面。

以下是我尝试运行的来自 asio 的 async_udp_echo_server 页面。

#include <cstdlib>
#include <iostream>
#include "asio.hpp"

using asio::ip::udp;

class server
{
public:
  server(asio::io_service& io_service, short port)
    : socket_(io_service, udp::endpoint(udp::v4(), port))
  {
    do_receive();
  }

  void do_receive()
  {
    socket_.async_receive_from(
        asio::buffer(data_, max_length), sender_endpoint_,
        [this](std::error_code ec, std::size_t bytes_recvd)
        {
          if (!ec && bytes_recvd > 0)
          {
            do_send(bytes_recvd);
          }
          else
          {
            do_receive();
          }
        });
  }

  void do_send(std::size_t length)
  {
    socket_.async_send_to(
        asio::buffer(data_, length), sender_endpoint_,
        [this](std::error_code /*ec*/, std::size_t /*bytes_sent*/)
        {
          do_receive();
        });
  }

private:
  udp::socket socket_;
  udp::endpoint sender_endpoint_;
  enum { max_length = 1024 };
  char data_[max_length];
};

int main(int argc, char* argv[])
{
  try
  {
    if (argc != 2)
    {
      std::cerr << "Usage: async_udp_echo_server <port>\n";
      return 1;
    }

    asio::io_service io_service;

    server s(io_service, std::atoi(argv[1]));

    io_service.run();
  }
  catch (std::exception& e)
  {
    std::cerr << "Exception: " << e.what() << "\n";
  }

  return 0;
}

最佳答案

由于您使用的是“独立”asioerror_code 应该是 asio::error_code 而不是 std::error_code。注意:boost::system::error_codeboost::asio 所必需的。

我使用以下宏在 boost 和“独立”asio 之间切换:

#ifdef ASIO_STANDALONE
  #include <asio.hpp>
  #define ASIO asio
  #define ASIO_ERROR_CODE asio::error_code
  #define ASIO_TIMER asio::steady_timer
#else
  #include <boost/asio.hpp>
  #define ASIO boost::asio
  #define ASIO_ERROR_CODE boost::system::error_code
  #define ASIO_TIMER boost::asio::deadline_timer
#endif

关于c++ - asio "std::error_code"没有在 eclipse 中解决?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39349913/

相关文章:

c++ - 为什么这个简单的 std::thread 示例不起作用?

c++ - boost::variant 的问题,链接器给出段错误

c++ - 覆盖 operator= 的返回类型

c++ - Eclipse/g++ 无法识别 "-std=c++11"标志

eclipse - 使用 eclipse 插件在 clearcase 环境中工作?

c++ - 为 C++ 字符串中的特殊符号 (") 赋予字面意义的有效 C++ 方法

c++ - 在 Qt 中获取耗时

java - 通过命令行将自定义属性传递给 PDE 构建

c++11 lambda高阶函数包装器递归错误

python - C++ std::vector 乘法中是否存在已知的不一致行为?