boost实现websocket(server)

本文介绍了如何使用Boost库中的Beast模块来实现WebSocket服务器,分别展示了同步和异步两种版本的代码实现。同步版本的server.cpp通过处理socket连接并在do_session中处理客户端消息。异步版本的async_server.cpp则采用层层异步调用来读取和响应客户端数据,并通过监听器listener处理连接。
摘要由CSDN通过智能技术生成

之前工作中用到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) {
         
  • 3
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
你可以使用第三方库来实现 C++WebSocket 服务器,比如 Boost.Beast 和 WebSocket++。 使用 Boost.Beast 实现 WebSocket 服务器的基本步骤如下: 1. 创建一个 TCP 服务器并监听指定端口。 2. 接受来自客户端的连接请求。 3. 在接受到连接请求后,握手协议。 4. 在握手成功后,接收和发送 WebSocket 消息。 5. 处理错误和断开连接。 下面是一个使用 Boost.Beast 实现的简单的 WebSocket 服务器的示例代码: ``` #include <boost/beast.hpp> #include <boost/asio.hpp> #include <iostream> #include <string> namespace beast = boost::beast; // from <boost/beast.hpp> namespace http = beast::http; // from <boost/beast/http.hpp> namespace net = boost::asio; // from <boost/asio.hpp> using tcp = net::ip::tcp; // from <boost/asio/ip/tcp.hpp> int main() { try { net::io_context ioc; tcp::acceptor acceptor(ioc, tcp::endpoint(tcp::v4(), 8080)); while (true) { tcp::socket socket(ioc); acceptor.accept(socket); // handshake beast::flat_buffer buffer; http::request<http::empty_body> req; http::read(socket, buffer, req); http::response<http::empty_body> res; res.set(http::field::sec_websocket_accept, req["sec-websocket-key"] + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"); res.result(http::status::switching_protocols); res.version(req.version()); http::write(socket, res); // read and write websocket data beast::websocket::stream<tcp::socket&> ws(socket); ws.accept(); while (true) { beast::flat_buffer buffer; ws.read(buffer); std::string message(beast::buffers_to_string(buffer.data())); if (message == "exit") { break; } ws.write(net::buffer(std::string("Server: ") + message)); } ws.close(beast::websocket::close_code::normal); } } catch (std::exception& e) { std::cerr << "Error: " << e.what() << std::endl; return 1; } return 0; } ``` 使用 WebSocket++ 实现 WebSocket 服务器的基本步骤如下: 1. 创建一个服务器并设置回调函数。 2. 接受来自客户端的连接请求。 3. 在接受到连接请求后,握手协议。 4. 在握手成功后,接收和发送 WebSocket 消息。 5. 处理错误和断开连接。 下面是一个使用 WebSocket++ 实现的简单的 WebSocket 服务器的示例代码: ``` #include <websocketpp/config/asio_no_tls.hpp> #include <websocketpp/server.hpp> #include <iostream> #include <string> using websocketpp::lib::placeholders::_1; using websocketpp::lib::placeholders::_2; using websocketpp::lib::bind; class Server { public: Server() { server_.set_access_channels(websocketpp::log::alevel::none); server_.clear_access_channels(websocketpp::log::alevel::none); server_.set_message_handler(bind(&Server::on_message, this, _1, _2)); } void run(uint16_t port) { server_.listen(port); server_.start_accept(); server_.run(); } private: void on_message(websocketpp::connection_hdl hdl, websocketpp::server<websocketpp::config::asio>*, websocketpp::frame::opcode::value opcode, std::string message) { if (opcode == websocketpp::frame::opcode::text) { if (message == "exit") { server_.stop(); } else { server_.send(hdl, "Server: " + message, opcode); } } } websocketpp::server<websocketpp::config::asio> server_; }; int main() { try { Server server; server.run(8080); } catch (websocketpp::exception const& e) { std::cerr << "Error: " << e.what() << std::endl; return 1; } return 0; } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值