boost库,websocket服务器

绑定client端的ip和port,监听client的消息,如果对方发送一个json格式的字符串,就给对方回复一个json格式的“type-join”

#include <boost/asio.hpp>
#include <boost/beast.hpp>
#include <boost/beast/websocket.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <iostream>
#include <string>

using namespace std;
namespace asio = boost::asio;
namespace websocket = boost::beast::websocket;
namespace property_tree = boost::property_tree;

int main()
{
    // 创建 asio 的 io_context
    asio::io_context io;

    // 创建一个 WebSocket 监听器
    websocket::listener listener(io);

    const string address = "127.0.0.1";  // 绑定的 IP 地址
    const short port = 8080;             // 绑定的端口号

    // 绑定 IP 和端口
    listener.set_option(asio::socket_base::reuse_address(true));
    listener.open(asio::ip::tcp::endpoint(asio::ip::make_address(address), port));

    // 开始监听
    listener.listen();

    cout << "Server started on " << address << ":" << port << endl;

    // 接受连接并处理 WebSocket 请求
    listener.async_accept([&](auto ec, auto socket) {
        if (ec) {
            cerr << "Accept error: " << ec.message() << endl;
            return;
        }

        // 接收消息
        socket.async_read([&](auto ec, auto buffer) {
            if (ec) {
                cerr << "Read error: " << ec.message() << endl;
                return;
            }

            // 将接收到的数据转换为字符串
            const string data = boost::beast::buffers_to_string(buffer.data());

            cout << "Received message: " << data << endl;

            // 解析 JSON 数据
            property_tree::ptree pt;
            property_tree::read_json(std::istringstream(data), pt);

            // 生成回复的字符串
            property_tree::ptree reply_pt;
            reply_pt.put("type", "join");
            std::ostringstream oss;
            property_tree::write_json(oss, reply_pt);

            // 回复消息
            const string reply_str = oss.str();
            socket.async_write(asio::buffer(reply_str), [&](auto ec, size_t) {
                if (ec) {
                    cerr << "Write error: " << ec.message() << endl;
                }
                else {
                    cout << "Sent message: " << reply_str << endl;
                }
                socket.close(websocket::close_code::normal);
                io.stop();
            });
        });
    });

    // 开始运行 io_context
    io.run();

    return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ZHANGα

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值