绑定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;
}