文档章节

boost实现websocket(server)

propagator
 propagator
发布于 05/23 22:21
字数 1085
阅读 16
收藏 0

之前工作中用到websocket,用boost.beast实现了客户端,原则上可以用了。不过既然涉及到这个问题,于是顺便研究了一下服务端如何实现。下面同样给出同步的版本和异步的版本。

 

先看看同步的版本

server.cpp

#include <boost/beast/core.hpp>
#include <boost/beast/websocket.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <cstdlib>
#include <functional>
#include <iostream>
#include <string>
#include <thread>

using tcp = boost::asio::ip::tcp;
namespace websocket = boost::beast::websocket;

// echoes back all received WebSocket messages
void do_session(tcp::socket& socket)
{
    try {
        // Construct the stream by moving in the socket
        websocket::stream<tcp::socket> ws{std::move(socket)};

        // Accept the websocket handshake
        ws.accept();

        for (;;) {
            // This buffer will hold the incoming message
            boost::beast::multi_buffer buffer;

            // Read a message
            ws.read(buffer);

            // Echo the message back
            ws.text(ws.got_text());
            ws.write(buffer.data());
        }
    } catch (boost::system::system_error const& se) {
        // This indicates that the session was closed
        if (se.code() != websocket::error::closed)
            std::cerr << "Error: " << se.code().message() << std::endl;
    } catch (std::exception const& e) {
        std::cerr << "Error: " << e.what() << std::endl;
    }
}

int main(int argc, char* argv[])
{
    try {
        // Check command line arguments
        if (argc != 3) {
            std::cerr << 
                "Usage: server <address> <port>\n" <<
                "Example:\n" <<
                "    server 0.0.0.0 8080\n";
            return EXIT_FAILURE;
        }
        auto const address = boost::asio::ip::make_address(argv[1]);
        auto const port = static_cast<unsigned short>(std::atoi(argv[2]));

        // The io_context is required for all I/O
        boost::asio::io_context ioc{1};

        // The acceptor receives incoming connections
        tcp::acceptor acceptor{ioc, {address, port}};
        for (;;) {
            // This will receive the new connection
            tcp::socket socket{ioc};

            // Block until we get a connection
            acceptor.accept(socket);

            // Launch the session, transferring ownership of the socket
            std::thread{std::bind(&do_session, std::move(socket))}.detach();
        }
    } catch (const std::exception& e) {
        std::cerr << "Error: " << e.what() << std::endl;
        return EXIT_FAILURE;
    }
}

可以看到这是一个非常简单的服务器,通过不断处理socket连接并在do_session中进行处理,将客户端发送过来的内容再返回给客户端。

 

接下来看看异步的版本

async_server.cpp

#include <boost/beast/core.hpp>
#include <boost/beast/websocket.hpp>
#include <boost/asio/bind_executor.hpp>
#include <boost/asio/strand.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <algorithm>
#include <cstdlib>
#include <functional>
#include <iostream>
#include <memory>
#include <string>
#include <thread>
#include <vector>

using tcp = boost::asio::ip::tcp;
namespace websocket = boost::beast::websocket;

//------------------------------------------------------------------------------

// Report a failure
void fail(boost::system::error_code ec, char const* what)
{
    std::cerr << what << ": " << ec.message() << "\n";
}

// Echoes back all received WebSocket messages
class session : public std::enable_shared_from_this<session>
{
    websocket::stream<tcp::socket> ws_;
    boost::asio::strand<
        boost::asio::io_context::executor_type> strand_;
    boost::beast::multi_buffer buffer_;

public:
    // Take ownership of the socket
    explicit session(tcp::socket socket)
        : ws_(std::move(socket))
        , strand_(ws_.get_executor())
    {
    }

    // Start the asynchronous operation
    void run()
    {
        // Accept the websocket handshake
        ws_.async_accept(
            boost::asio::bind_executor(
                strand_,
                std::bind(
                    &session::on_accept,
                    shared_from_this(),
                    std::placeholders::_1)));
    }

    void on_accept(boost::system::error_code ec)
    {
        if(ec) return fail(ec, "accept");

        // Read a message
        do_read();
    }

    void do_read()
    {
        // Read a message into our buffer
        ws_.async_read(
            buffer_,
            boost::asio::bind_executor(
                strand_,
                std::bind(
                    &session::on_read,
                    shared_from_this(),
                    std::placeholders::_1,
                    std::placeholders::_2)));
    }

    void on_read(
        boost::system::error_code ec,
        std::size_t bytes_transferred)
    {
        boost::ignore_unused(bytes_transferred);

        // This indicates that the session was closed
        if(ec == websocket::error::closed) return;

        if(ec) fail(ec, "read");

        // Echo the message
        ws_.text(ws_.got_text());
        ws_.async_write(
            buffer_.data(),
            boost::asio::bind_executor(
                strand_,
                std::bind(
                    &session::on_write,
                    shared_from_this(),
                    std::placeholders::_1,
                    std::placeholders::_2)));
    }

    void on_write(
        boost::system::error_code ec,
        std::size_t bytes_transferred)
    {
        boost::ignore_unused(bytes_transferred);

        if(ec) return fail(ec, "write");

        // Clear the buffer
        buffer_.consume(buffer_.size());

        // Do another read
        do_read();
    }
};

//------------------------------------------------------------------------------

// Accepts incoming connections and launches the sessions
class listener : public std::enable_shared_from_this<listener>
{
    tcp::acceptor acceptor_;
    tcp::socket socket_;

public:
    listener(
        boost::asio::io_context& ioc,
        tcp::endpoint endpoint)
        : acceptor_(ioc)
        , socket_(ioc)
    {
        boost::system::error_code ec;

        // Open the acceptor
        acceptor_.open(endpoint.protocol(), ec);
        if(ec)
        {
            fail(ec, "open");
            return;
        }

        // Allow address reuse
        acceptor_.set_option(boost::asio::socket_base::reuse_address(true), ec);
        if(ec)
        {
            fail(ec, "set_option");
            return;
        }

        // Bind to the server address
        acceptor_.bind(endpoint, ec);
        if(ec)
        {
            fail(ec, "bind");
            return;
        }

        // Start listening for connections
        acceptor_.listen(
            boost::asio::socket_base::max_listen_connections, ec);
        if(ec)
        {
            fail(ec, "listen");
            return;
        }
    }

    // Start accepting incoming connections
    void run()
    {
        if(! acceptor_.is_open())
            return;
        do_accept();
    }

    void do_accept()
    {
        acceptor_.async_accept(
            socket_,
            std::bind(
                &listener::on_accept,
                shared_from_this(),
                std::placeholders::_1));
    }

    void on_accept(boost::system::error_code ec)
    {
        if(ec)
        {
            fail(ec, "accept");
        }
        else
        {
            // Create the session and run it
            std::make_shared<session>(std::move(socket_))->run();
        }

        // Accept another connection
        do_accept();
    }
};

//------------------------------------------------------------------------------

int main(int argc, char* argv[])
{
    // Check command line arguments.
    if (argc != 4)
    {
        std::cerr <<
            "Usage: async_server <address> <port> <threads>\n" <<
            "Example:\n" <<
            "    async_server 0.0.0.0 8080 1\n";
        return EXIT_FAILURE;
    }
    auto const address = boost::asio::ip::make_address(argv[1]);
    auto const port = static_cast<unsigned short>(std::atoi(argv[2]));
    auto const threads = std::max<int>(1, std::atoi(argv[3]));

    // The io_context is required for all I/O
    boost::asio::io_context ioc{threads};

    // Create and launch a listening port
    std::make_shared<listener>(ioc, tcp::endpoint{address, port})->run();

    // Run the I/O service on the requested number of threads
    std::vector<std::thread> v;
    v.reserve(threads - 1);
    for(auto i = threads - 1; i > 0; --i)
        v.emplace_back(
        [&ioc]
        {
            ioc.run();
        });
    ioc.run();

    return EXIT_SUCCESS;
}

可以看到异步服务器端和异步客户端类似,均是层层异步调用,只是session write后没有结束,又接着调用do_read。此外增加了一个监听器listener,在建立连接后,让session处理接下来的工作,读取socket内容,通过websocket流再写回去。

© 著作权归作者所有

propagator
粉丝 8
博文 39
码字总数 44624
作品 0
昆明
私信 提问
【求助】谁知道 node-websocket-server 框架怎么用,麻烦帮忙看一下

本人是名在校大三学生,刚接触nodejs不到一个星期,看了node入门 然后主要是想用nodejs结合websocket和WebGL搞一个小开发,正好在本站和其他地方都有许多讲nodejs与websocket结合的文章,其中在w...

冯焰
2012/02/04
1K
2
boost实现websocket(client)

最近需要在c++程序中用到websocket技术,上网查了一下,找到四个库:libwebsocket, websocketpp, mongoose, boost.beast. 因为项目已经依赖于boost了,而且版本也比较新1.68,可以直接用boo...

propagator
01/05
0
0
基于WebSocet简单聊天室(NodeJS + node-websocket-server)

最近在学习HTML5相关的东西,看到WebSocket是个很强大的技术,于是乎就小试了一下,做了个简单的聊天室。 WebSocket的原理就不多介绍了,如果想自己实现WebSocket服务器的话具体协议看这里:...

lion_yang
2011/08/28
0
36
用jetty搭建websocket服务并与ie78兼容的方法

jetty8中已经自带有websocket功能,所以我们可以很方便搭建一个自己的websocket服务。 源程序:http://sdrv.ms/N5BuKw 启动类:org.noahx.websocket.WebSocketServer 访问地址:http://127....

NoahX
2012/08/09
0
6
websocket与node.js的完美结合

本文为原创文章,出自http://cnodejs.org,转载请注明出处和作者 作者:kongwu 原文:http://cnodejs.org/blog/?p=273 之所以写下此文,是我觉得越是简单的技术往往能发挥越重要的作用,随着...

红薯
2011/03/20
9.7K
2

没有更多内容

加载失败,请刷新页面

加载更多

lua字符串和时间戳相互转换

1. 时间戳转成格式化字符串 直接利用函数os.date()将时间戳转化成格式化字符串.```local timestamp = 1561636137;local strDate = os.date("%Y/%m/%d %H:%M:%S", timestamp)print("strD......

书香神
39分钟前
1
0
代码规范

代码格式化 安装vscode插件:Prettier - Code formatter 格式化配置:将下列配置写入到vscode的settings.json文件 (遵照代码格式化) "prettier.disableLanguages": ["vue"], "prettier.......

TreeZhou0511
今天
5
0
python实现人工神经网络的一个例子

人工神经网络已经有无数的开源框架,比如tensorflow,caffe等,可以直接用。但最近需要做一个小样例,把基本思想讲一讲,因此自己写了一个demo,以供参考。 下面直接上代码,代码中有注释,比...

propagator
今天
6
0
远程dubugger

1、在tomcat的bin下/data/project/XXX/apache-tomcat-8.5.23/bin 在catalina.bat文件中新增如下即可 JAVA_OPTS="-Xmx1024m -Xms1024m -agentlib:jdwp=transport=dt_socket,server=y,suspend......

一只小青蛙
今天
3
0
jemter 连接MySQL

jemter 连接MySQL 点击测试计划,测试计划最后”添加目录或jar包到ClassPath“,点击浏览,添加mysql-connector.jar mysql-connector.jar的下载地址: https://mvnrepository.com/artifact/my...

xiaobai1315
今天
6
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部