zoukankan      html  css  js  c++  java
  • socket通信框架——boost asio

    boost asio是一个封装了基本socket的跨平台通信框架。它支持异步访问,并支持tcp的自动封闭控制等操作。

    一个简单的通信协议可以为:

    header body
    body长 数据

    通过boost::asio接收的话,即可为:

    void receive_header()
    {
      auto keep_alive(shared_from_this());
      auto asbuf = boost::asio::buffer(msg->header(), msg->header_length());
      auto on_header_received = [this, keep_alive]
        (boost::system::error_code ec, std::size_t length)
      {
        if (!ec && buffer->decode_header())
        {
          receive_body();
        }
      };
    
      boost::asio::async_read(socket_id, asbuf, on_header_received);
    }
    
    void receive_body()
    {
      auto keep_alive(shared_from_this());
      auto asbuf = boost::asio::buffer(msg->body(), msg->body_length());
      auto on_body_received = [this, keep_alive]
        (boost::system::error_code ec, std::size_t length)
      {
        if (!ecode && msg->body_length())
        {
          // do something
        }
        receive_header();
      }
    
      boost::asio::async_read(socket_id, asbuf, on_body_received);
    }

    而一个简单的发送数据端可为:

    void send(Message msg)
    {
      boost::system::error_code ec;
      std::uint32_t posted = 0;
      std::uint32_t rest = msg.length();
    
      msg.encode_header();
    
      do 
    { auto asbuf
    = boost::asio::buffer(msg.data() + posted, rest); posted = _socket.write_some(asbuf, ec); if (ec) { break; } rest -= posted; } while (rest > 0); }

    资料参考:

    https://www.cnblogs.com/fnlingnzb-learner/p/10408812.html

  • 相关阅读:
    Python 01 Python的安装和配置
    Python 04 Geany的安装和配置
    Python 02 编写代码
    Python 03 pip 的安装和使用
    开源项目 12 ServiceStack.OrmLite
    北京第二天
    exit
    北京第一天
    关于扩展欧几里得算法和逆元
    正妹吃月饼
  • 原文地址:https://www.cnblogs.com/qyit/p/13389547.html
Copyright © 2011-2022 走看看