c ++ websocketpp等待答案

时间:2019-02-19 15:17:16

标签: c++ multithreading websocket

我通过http-server获得主线程,而通过Websocketpp客户端获得后台线程,该线程必须将消息发送到Websocket服务器。我尝试从主线程发送一些数据,并将其用于全局变量。看起来像:

全局变量:

extern client* SendClient; //for sending message
extern websocketpp::connection_hdl hdlSend;
extern nlohmann::json Result; //for get result

WebSocket:

void on_open(client* c, websocketpp::connection_hdl hdl, std::string sid, std::string type, std::string streamName) {

    std::cout << "SET CONNECTION TO STREAM " << std::endl;

    hdlSend = hdl;
    SendClient = c;

    std::string resp = "Start";
    c->send(hdl, resp, websocketpp::frame::opcode::text);


}

void on_message(client* c, websocketpp::connection_hdl hdl, message_ptr msg, std::string sid, std::string types) {

    std::string GetMess = msg->get_payload();
    function FUNC;

    if (DEBUG == true)
        FUNC.make_log("DEBUG", "Get Mess: " + GetMess, false);

    Result.clear();

    try {
    Result = nlohmann::json::parse(GetMess);
    }
    catch (nlohmann::json::parse_error e) {
        Result["code"] = -1;
    }


    websocketpp::lib::error_code ec;


    if (ec) {
        std::cout << "Echo failed because: " << ec.message() << std::endl;
    }
}


run()
{

std::string uri = "wss://0.0.0.0:4477/";


    client c;

    try {
        c.set_access_channels(websocketpp::log::alevel::all);
        c.clear_access_channels(websocketpp::log::alevel::frame_payload);


        c.init_asio();
        c.set_tls_init_handler(bind(&on_tls_init));

        c.set_message_handler(bind(&on_message, &c, ::_1, ::_2, sid, type));
        c.set_open_handler(bind(&on_open, &c, ::_1, sid, type, streamName));
        c.set_close_handler(bind(&on_close, &c, ::_1, type, sid));


        websocketpp::lib::error_code ec;
        client::connection_ptr con = c.get_connection(uri, ec);
        if (ec) {
            std::cout << "could not create connection because: " << ec.message() << std::endl;

        }


        c.connect(con);

        c.run();

}

和测试代码。我在线程中调用WebSocket服务器-> sleep等待连接,然后发送2条消息

std::thread CachingTh(CachingRun); 
CachingTh.detach(); // send WebSocket to background thread

SendClient->get_con_from_hdl(hdlSend)->send("Start", websocketpp::frame::opcode::text); // Send hello, server must return "Start"



nlohmann::json Send;
Send["type"] = "Setint";
Send["key"] = "test";
Send["value"] = "test"; 

SendClient->get_con_from_hdl(hdlSend)->send(Send.dump(), websocketpp::frame::opcode::text); // Send json, server must return "is_ok"

std::cout << "Result: " << Result.dump() << std::endl; // get result

std::cout << "**********************" << std::endl;

此后,我得到:

Get Mess: Start
Get Mess: is_ok
CachResult: Start

但必须为:

Get Mess: Start
Get Mess: is_ok
CachResult: is_ok

然后我如何理解客户端必须等待WebSocket服务器的答复。您能帮我,如何正确执行上述任务?谢谢!

0 个答案:

没有答案
相关问题