boost asio学习笔记(2) echo 客户端

#include <iostream>
#include <memory>
#include <array>
#include <boost/asio.hpp>
using namespace std;
using namespace boost::asio;

const int MAX_MESS_SIZE = 4096;

class Session : public enable_shared_from_this < Session >
{
public:
    Session(ip::tcp::socket &st) : m_socket(st), m_buff({})
    {
    }

    void write_to_socket()
    {
        auto shared_self(shared_from_this());
        async_write(m_socket, buffer(m_buff), [this, shared_self](const boost::system::error_code &err, size_t length)
        {
            if (!err)
            {
                read_from_socket();
            }
        });
    }

    void read_from_socket()
    {
        auto shared_self(shared_from_this());
        m_socket.async_read_some(buffer(m_buff), [this, shared_self](const boost::system::error_code &err, size_t length)
        {
            if (!err)
            {
                write_to_socket();
            }
        });
    }

private:
    ip::tcp::socket &m_socket;
    array<char, MAX_MESS_SIZE> m_buff;
};

class Client
{
public:
    Client(io_service &ios) : m_ios(ios), m_sock(m_ios)
    {
    }

    void start_connect()
    {
        cout << "start connect" << endl;
        auto ptr = make_shared<Session>(m_sock);
        m_sock.async_connect(ip::tcp::endpoint(ip::address::from_string("127.0.0.1"), 8001), [this, ptr](const boost::system::error_code &err)
        {
            if (!err)
            {
                ptr->write_to_socket();
            }
        });
    }

private:
    io_service &m_ios;
    ip::tcp::socket m_sock;
};

int main()
{
    io_service io;
    Client cli(io);

    cli.start_connect();

    io.run();

    return 0;
}

客户端运行后:
这里写图片描述

运行服务端再运行客户端后:
这里写图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值