You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
48 lines
1.2 KiB
48 lines
1.2 KiB
#include <iostream>
|
|
#include <string>
|
|
#include <websocketpp/config/asio_no_tls.hpp>
|
|
#include <websocketpp/server.hpp>
|
|
#include <nlohmann/json.hpp>
|
|
|
|
using json = nlohmann::json;
|
|
using websocketpp::lib::placeholders::_1;
|
|
using websocketpp::lib::placeholders::_2;
|
|
using websocketpp::lib::bind;
|
|
|
|
typedef websocketpp::server<websocketpp::config::asio> server;
|
|
|
|
// 消息处理回调函数
|
|
void on_message(server* s, websocketpp::connection_hdl hdl, server::message_ptr msg) {
|
|
std::string payload = msg->get_payload();
|
|
std::cout << "Received JSON string: " << payload << std::endl;
|
|
|
|
// 解析JSON字符串
|
|
try {
|
|
json j = json::parse(payload);
|
|
std::cout << "Parsed JSON: " << j.dump(4) << std::endl; // 使用dump(4)美化输出
|
|
}
|
|
catch (json::parse_error& e) {
|
|
std::cerr << "Failed to parse JSON: " << e.what() << std::endl;
|
|
}
|
|
}
|
|
|
|
int main() {
|
|
server ws_server;
|
|
|
|
// 初始化服务器
|
|
ws_server.init_asio();
|
|
|
|
// 设置消息处理回调
|
|
ws_server.set_message_handler(bind(&on_message, &ws_server, ::_1, ::_2));
|
|
|
|
// 监听端口
|
|
ws_server.listen(8081);
|
|
|
|
// 启动服务器
|
|
ws_server.start_accept();
|
|
|
|
// 运行服务器
|
|
ws_server.run();
|
|
|
|
return 0;
|
|
}
|