您当前的位置: 首页 >  websocket

qianbo_insist

暂无认证

  • 0浏览

    0关注

    399博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

如何正确写c++ boost beast websocket server

qianbo_insist 发布时间:2022-07-10 10:20:08 ,浏览量:0

websocket server

这里有一个要求,就是获取客户端或者浏览器的url 请求路由 在这里插入图片描述 1 我们在path里面打印路径 2 我们显示beast 里的flat_buffer 的数据,根据最新的api

实际上,beast 的文档里面详细说明了如何获取路由,我给大家摘出来:路径在boost的文档lib下handshaking.html里面 libs/beast/doc/html/beast/using_websocket/handshaking.html

// This buffer is required for reading HTTP messages
flat_buffer buffer;

// Read the HTTP request ourselves
http::request req;
http::read(sock, buffer, req);

// See if its a WebSocket upgrade request
if(websocket::is_upgrade(req))
{
    // Construct the stream, transferring ownership of the socket
    stream ws(std::move(sock));

    // Clients SHOULD NOT begin sending WebSocket
    // frames until the server has provided a response.
    BOOST_ASSERT(buffer.size() == 0);

    // Accept the upgrade request
    ws.accept(req);
}
else
{
    // Its not a WebSocket upgrade, so
    // handle it like a normal HTTP request.
}

那么相应使用异步代码的时候,我们就要改成异步的接收

        beast::flat_buffer buffer;

        // Read the HTTP request ourselves
        http::request req;
        http::read(ws_.next_layer(), buffer, req);

        // See if its a WebSocket upgrade request
        if (websocket::is_upgrade(req))
        {
            // Construct the stream, transferring ownership of the socket
            //stream ws(std::move(sock));

            // Clients SHOULD NOT begin sending WebSocket
            // frames until the server has provided a response.
            BOOST_ASSERT(buffer.size() == 0);

            // Accept the upgrade request


            ws_.async_accept(req,
                beast::bind_front_handler(
                    &session::on_accept,
                    shared_from_this()));

            printf("path: %s\n", std::string(req.target().data(), req.target().length()).data());
        }
    }

我们知道本身websocket协议是建立在http协议之上,实际上只是头部字节需要upgrade。可以参考我自己写的websocket server,在我的文章里面,没有使用其他库,纯粹自己把websocket协议实现了。

2 、就是缓冲区,boost的缓冲区都是封装好的,我么需要解出来

asio 的streambuf 我们要这样解开:

boost::asio::streambuf sb;
...
std::size_t n = boost::asio::read_until(sock, sb, '\n');
boost::asio::streambuf::const_buffers_type bufs = sb.data();
std::string line(
    boost::asio::buffers_begin(bufs),
    boost::asio::buffers_begin(bufs) + n);

beast 的缓冲区根据最新的文档,要使用 boost::beast::make_printable(buffer_.data()); 而不是以前的cast了

    // Echo the message
        std::stringstream ss; 
        ss 
    

    
        function WebSocketTest() {
            if ("WebSocket" in window) {
                // alert("您的浏览器支持 WebSocket!");

                // 打开一个 web socket
                var ws = new WebSocket("ws://127.0.0.1:80/live/1001");
                console.log(ws);
                ws.onopen = function (evt) {
                    // Web Socket 已连接上,使用 send() 方法发送数据
 
                    console.log(evt)
                    let obj = JSON.stringify({
                        type: 'send',
                        data: {
                            text: 'china',
                            userId: '001',
                            userName: 'qianbo'
                        }
                    })
                    ws.send(obj);
                    console.log("数据发送中...");
                };

                ws.onmessage = function (evt) {
                    var received_msg = JSON.parse(evt.data);

                    console.log(received_msg)
					alert(received_msg.data.userName);
                };

                ws.onclose = function () {
                    // 关闭 websocket
                    alert("连接已关闭...");
                };
            } else {
                // 浏览器不支持 WebSocket
                alert("您的浏览器不支持 WebSocket!");
            }
        }
    


    
        运行 WebSocket
    


代码里发送一些数据,控制台打印数据并且alert 一个json里面的一个成员变量

服务端代码如下:
//
// Copyright (c) 2016-2019 Vinnie Falco (vinnie dot falco at gmail dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// Official repository: https://github.com/boostorg/beast
//

//------------------------------------------------------------------------------
//
// Example: WebSocket server, asynchronous
//
//------------------------------------------------------------------------------
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
namespace beast = boost::beast;         // from 
namespace http = boost::beast::http;           // from 
namespace websocket = beast::websocket; // from 
namespace net = boost::asio;            // from 
using tcp = boost::asio::ip::tcp;       // from 

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

// Report a failure
void
fail(beast::error_code ec, char const* what)
{
    std::cerr             
关注
打赏
1663161521
查看更多评论
0.1686s