asio(八)、异步TCP服务器

该文介绍了一个基于Asio库构建的异步TCP服务器的示例,服务器监听端口13,接收连接并发送当前时间给客户端。核心组件包括io_context对象,用于管理I/O服务,以及tcp_server和tcp_connection类,分别处理新连接的接受和数据传输。tcp_connection使用async_write确保完整数据块的发送,并在写操作完成后进行处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

官网教程:https://think-async.com/Asio/asio-1.26.0/doc/asio/tutorial/tutdaytime3.html

异步TCP服务器

int main()
{
  try
  {

我们需要创建一个服务器对象来接受传入的客户端连接。io_context对象提供服务器对象将使用的I/O服务,例如套接字。

    asio::io_context io_context;
    tcp_server server(io_context);

运行io_context对象,以便它代表您执行异步操作。


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

  return 0;
}

tcp_server类

class tcp_server
{
public:

构造函数初始化一个接收器以侦听TCP端口13。

  tcp_server(asio::io_context& io_context)
    : io_context_(io_context),
      acceptor_(io_context, tcp::endpoint(tcp::v4(), 13))
  {
    start_accept();
  }

private:

函数start_accept()创建一个套接字,并启动异步接受操作以等待新的连接。

  void start_accept()
  {
    tcp_connection::pointer new_connection =
      tcp_connection::create(io_context_);

    acceptor_.async_accept(new_connection->socket(),
        boost::bind(&tcp_server::handle_accept, this, new_connection,
          asio::placeholders::error));
  }

函数handle_accept()在start_accept()启动的异步接受操作完成时调用。它为客户端请求提供服务,然后调用start_accept()来启动下一个accept操作。

  void handle_accept(tcp_connection::pointer new_connection,
      const asio::error_code& error)
  {
    if (!error)
    {
      new_connection->start();
    }

    start_accept();
  }

tcp_connection类

我们将使用shared_ptr和enable_shared_from_this,因为只要有引用tcp_connection对象的操作,我们就希望它保持活动状态。

class tcp_connection
  : public boost::enable_shared_from_this<tcp_connection>
{
public:
  typedef boost::shared_ptr<tcp_connection> pointer;

  static pointer create(asio::io_context& io_context)
  {
    return pointer(new tcp_connection(io_context));
  }

  tcp::socket& socket()
  {
    return socket_;
  }

在函数start()中,我们调用asio::async_write()将数据提供给客户端。请注意,我们使用的是asio::async_write(),而不是ip::tcp::socket::async_write_some(),以确保发送整个数据块。

  void start()
  {

要发送的数据存储在类成员message_中,因为我们需要在异步操作完成之前保持数据的有效性。

    message_=make_daytime_string()

启动异步操作时,如果使用boost::bind,则必须仅指定与处理程序的参数列表匹配的参数。在这个程序中,两个参数占位符(asio::placeholders::error和asio::placeholders::bytes_transfered)可能已经被删除,因为它们没有在handle_write()中使用。

    asio::async_write(socket_, asio::buffer(message_),
        boost::bind(&tcp_connection::handle_write, shared_from_this(),
          asio::placeholders::error,
          asio::placeholders::bytes_transferred));

这个客户端连接的任何进一步操作现在都由handle_write()负责。

  }

private:
  tcp_connection(asio::io_context& io_context)
    : socket_(io_context)
  {
  }

  void handle_write(const asio::error_code& /*error*/,
      size_t /*bytes_transferred*/)
  {
  }

  tcp::socket socket_;
  std::string message_;
};

正在删除未使用的处理程序参数

您可能已经注意到,handle_write()函数的主体中没有使用错误和bytes_transfered参数。如果不需要参数,可以将它们从函数中删除,使其看起来像:

  void handle_write()
  {
  }

用于启动调用的asio::async_write()调用可以更改为仅:

  asio::async_write(socket_, asio::buffer(message_),
      boost::bind(&tcp_connection::handle_write, shared_from_this()));
#include <ctime>
#include <iostream>
#include <string>
#include <boost/bind/bind.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/enable_shared_from_this.hpp>
#include <asio.hpp>

using asio::ip::tcp;

std::string make_daytime_string()
{
  using namespace std; // For time_t, time and ctime;
  time_t now = time(0);
  return ctime(&now);
}

class tcp_connection
  : public boost::enable_shared_from_this<tcp_connection>
{
public:
  typedef boost::shared_ptr<tcp_connection> pointer;

  static pointer create(asio::io_context& io_context)
  {
    return pointer(new tcp_connection(io_context));
  }

  tcp::socket& socket()
  {
    return socket_;
  }

  void start()
  {
    message_ = make_daytime_string();

    asio::async_write(socket_, asio::buffer(message_),
        boost::bind(&tcp_connection::handle_write, shared_from_this(),
          asio::placeholders::error,
          asio::placeholders::bytes_transferred));
  }

private:
  tcp_connection(asio::io_context& io_context)
    : socket_(io_context)
  {
  }

  void handle_write(const asio::error_code& /*error*/,
      size_t /*bytes_transferred*/)
  {
  }

  tcp::socket socket_;
  std::string message_;
};

class tcp_server
{
public:
  tcp_server(asio::io_context& io_context)
    : io_context_(io_context),
      acceptor_(io_context, tcp::endpoint(tcp::v4(), 13))
  {
    start_accept();
  }

private:
  void start_accept()
  {
    tcp_connection::pointer new_connection =
      tcp_connection::create(io_context_);

    acceptor_.async_accept(new_connection->socket(),
        boost::bind(&tcp_server::handle_accept, this, new_connection,
          asio::placeholders::error));
  }

  void handle_accept(tcp_connection::pointer new_connection,
      const asio::error_code& error)
  {
    if (!error)
    {
      new_connection->start();
    }

    start_accept();
  }

  asio::io_context& io_context_;
  tcp::acceptor acceptor_;
};

int main()
{
  try
  {
    asio::io_context io_context;
    tcp_server server(io_context);
    io_context.run();
  }
  catch (std::exception& e)
  {
    std::cerr << e.what() << std::endl;
  }

  return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值