基本Boost :: asio TCP客户端

时间:2017-04-23 10:21:20

标签: c++ sockets boost tcp boost-asio

我正在尝试创建基本的异步TCP客户端,输出它收到的任何内容。这是我的代码:

class tcp_client
{
private:
  std::shared_ptr<tcp::socket> socket;
  std::array<char, 1024> recv_buf;

public:
  tcp_client(boost::asio::io_service& io_service)
  {     
        socket = std::make_shared<tcp::socket>(io_service);
        socket->connect(tcp::endpoint(boost::asio::ip::address::from_string("127.0.0.1"), 2522));

        start_receive();
  }

private:
  void start_receive()
  {

    socket->async_receive(boost::asio::buffer(recv_buf),
        boost::bind(&tcp_client::handle_receive, this,
          boost::asio::placeholders::error));
  }

  void handle_receive(const boost::system::error_code& error)
  {
        std::cout << "handling receive: " << error << ": " << error.message() << std::endl;
        std::cout << std::string(recv_buf.data()) << std::endl;

        start_receive();
  }

};

int main()
{
    boost::asio::io_service io_service;
    tcp_client client(io_service);
    io_service.run();
    return 0;
}

这很简单:

  1. 创建套接字并连接到本地端口2522(这可能是错误发生的地方)
  2. 套接字设置为async_receive并设置为具有处理程序(但从未到达此部分)
  3. 处理程序设置为处理接收的数据并重新启动套接字
  4. 代码产生以下运行时错误:

    boost::exception_detail::clone_impl<boost::exception_detail::error_info_injector<boost::system::system_error> >: connect: Connection refused
    

0 个答案:

没有答案