测试文本
{
"method": "login",
"params":
{
"username": "张三",
"password": "123"
}
}```
#include <websocketpp/config/asio_no_tls.hpp>
#include <websocketpp/server.hpp>
#include "rapidjson/rapidjson.h"
#include "rapidjson/document.h"
#include "rapidjson/filereadstream.h"
#include "rapidjson/filewritestream.h"
#include "rapidjson/stringbuffer.h"
#include "rapidjson/writer.h"
#include <iostream>
typedef websocketpp::server<websocketpp::config::asio> server;
using websocketpp::lib::placeholders::_1;
using websocketpp::lib::placeholders::_2;
using websocketpp::lib::bind;
// pull out the type of messages sent by our config
typedef server::message_ptr message_ptr;
// Define a callback to handle incoming messages
void on_message(server* s, websocketpp::connection_hdl hdl, message_ptr msg) {
std::cout << "on_message called with hdl: " << hdl.lock().get()
<< " and message: " << msg->get_payload()
<< std::endl;
rapidjson::Document recvMsg;
recvMsg.Parse<0>(msg->get_payload().c_str());
if (recvMsg.HasParseError())
{
rapidjson::ParseErrorCode code = recvMsg.GetParseError();
std::cout << "Error code " << code << std::endl;
}
std::cout << std::endl<<"json parse success" << std::endl;
try
{
if (recvMsg.HasMember("method"))
{
rapidjson::Value &jsonMethod = recvMsg["method"];
std::string strMethod = jsonMethod.GetString();
if (strMethod == "login")
{
if (recvMsg.HasMember("params"))
{
rapidjson::Value& jsonParam = recvMsg["params"];
if (jsonParam.IsObject())
{
if (jsonParam.HasMember("username"))
{
std::cout << std::endl << "name" << jsonParam["username"].GetString() << std::endl;
}
if (jsonParam.HasMember("password"))
{
std::cout << std::endl << "password" << jsonParam["password"].GetString() << std::endl;
}
}
}
}
}
}
catch (...)
{
std::cout << std::endl << "get value failed" << std::endl;
}
// check for a special command to instruct the server to stop listening so
// it can be cleanly exited.
if (msg->get_payload() == "stop-listening") {
s->stop_listening();
return;
}
try {
s->send(hdl, msg->get_payload(), msg->get_opcode());
}
catch (websocketpp::exception const & e) {
std::cout << "Echo failed because: "
<< "(" << e.what() << ")" << std::endl;
}
}
int main() {
// Create a server endpoint
server echo_server;
try {
// Set logging settings
echo_server.set_access_channels(websocketpp::log::alevel::all);
echo_server.clear_access_channels(websocketpp::log::alevel::frame_payload);
// Initialize Asio
echo_server.init_asio();
// Register our message handler
echo_server.set_message_handler(bind(&on_message, &echo_server, ::_1, ::_2));
// Listen on port 9002
echo_server.listen(9002);
// Start the server accept loop
echo_server.start_accept();
// Start the ASIO io_service run loop
echo_server.run();
}
catch (websocketpp::exception const & e) {
std::cout << e.what() << std::endl;
}
catch (...) {
std::cout << "other exception" << std::endl;
}
}