'How to stream data with websocket with cpprest?

I have a cpprestsdk package and using to connect and stream data from some endpoint.

using namespace web;
using namespace web::websockets::client;
websocket_client clientbtcusdt;
clientbtcusdt.connect(std::wstring(L"wss://stream.binance.com:9443/ws/" + std::wstring(L"btcusdt") + L"@depth20@100ms")).wait();
clientbtcusdt.receive().then([](websocket_incoming_message in_msg)
    {
        return in_msg.extract_string();
    }).then([&](std::string body)
        {
            Json::Value json;
            std::string parsingError;
            std::stringstream streamResponse(body);
            Json::parseFromStream(Json::CharReaderBuilder(), streamResponse, &json, &parsingError);
            std::cout << json << std::endl;
        }).wait();

This receives one json message and then closes connection.

How can I stream permanently?
If I would stream permanently by wrapping this into infinite loop and then want few such streams, should wrap every infinite loop into callable and attach a thread to every such socket?



Solution 1:[1]

You should use websocket_callback_client instead of websocket_client.

please see this:

Sometimes if you need to receive a lot of messages from the server it can be tedious and error prone to repeatedly call and handle each task. We have another class that allows setting a callback for messages from the server. Here is a simple example registering a callback:websocket_client::receive()websocket_callback_client

keep receiving message from websocket

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 chen1900