美文网首页
boost asio实现简单echo服务器

boost asio实现简单echo服务器

作者: 一路向后 | 来源:发表于2022-02-28 22:23 被阅读0次

1.源码实现

#include <iostream>
#include <string>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/smart_ptr.hpp>

using namespace std;

class EchoServer {
public:
    EchoServer(boost::asio::io_service &iosev) : m_service(iosev), m_acceptor(iosev, boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), 80)) {}

    /*创建一个tcp的socket*/
    void start()
    {
        boost::shared_ptr<boost::asio::ip::tcp::socket> p_socket(new boost::asio::ip::tcp::socket(m_service));

        m_acceptor.async_accept(*p_socket, boost::bind(&EchoServer::accept, this, p_socket, _1));
    }

    /*有客户端连接时触发*/
    void accept(boost::shared_ptr<boost::asio::ip::tcp::socket> socket, boost::system::error_code ec)
    {
        if(ec)
        {
            return;
        }

        /*继续等待连接*/
        start();

        /*发送信息*/
        boost::shared_ptr<std::string> pstr(new std::string("hello async world!"));

        socket->async_write_some(boost::asio::buffer(*pstr), boost::bind(&EchoServer::write, this, pstr, _1, _2));
    }

    void write(boost::shared_ptr<std::string> pstr, boost::system::error_code ec, size_t bytes_transferred)
    {

    }

private:
    boost::asio::io_service &m_service;
    boost::asio::ip::tcp::acceptor m_acceptor;

};

int main()
{
    boost::asio::io_service io_servie;
    EchoServer srv(io_servie);

    srv.start();

    io_servie.run();

    return 0;
}

2.编译源码

$ g++ -o test test.cpp -std=c++11  -lboost_system

3.运行及其结果

$ sudo ./test
$ telnet localhost 80
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
hello async world!Connection closed by foreign host.

相关文章

网友评论

      本文标题:boost asio实现简单echo服务器

      本文链接:https://www.haomeiwen.com/subject/zxprrrtx.html