如何使用cpprestsdk设置WebSocket SSL连接?

时间:2019-07-04 09:37:06

标签: ssl websocket

我尝试使用SSL连接到Websocket服务器。但是总是在连接失败(...)。 我是cpprestsdk的新手,我找不到有关如何将SSL信息设置为websocket_client的文档。

websocket_client_config config;
config.set_server_name("wss://host:port/v3/api");
websocket_client client(config);

auto fileStream = std::make_sharedconcurrency::streams::ostream();
pplx::task requestTask = fstream::open_ostream(U("results2.html"))
.then([&](ostream outFile)
{
*fileStream = outFile;
// Create http_client to send the request.
uri wsuri(U("wss://host:port/v3/api"));
client.connect(wsuri).wait();

     websocket_outgoing_message msg;
     msg.set_utf8_message(obj.serialize());
     client.send(msg).wait();
     printf("send success: %s\n", obj.serialize().c_str());
     return client.receive().get();
})

它抛出“错误异常:set_fail_handler:8:TLS握手失败”。

1 个答案:

答案 0 :(得分:0)

cpprestsdk的文档可以在这里找到 C++ REST SDK WebSocket client。尽管这不会显示与cpprestsdk相关的所有必要信息,但对您有帮助。

您还可以获得SSL测试示例here。我展示了一个使用SSL或wss://方案实现的简单websocket客户端

 websocket_client client;
        std::string body_str("hello");

        try
        {
            client.connect(U("wss://echo.websocket.org/")).wait();
            auto receive_task = client.receive().then([body_str](websocket_incoming_message ret_msg) {
                VERIFY_ARE_EQUAL(ret_msg.length(), body_str.length());
                auto ret_str = ret_msg.extract_string().get();

                VERIFY_ARE_EQUAL(body_str.compare(ret_str), 0);
                VERIFY_ARE_EQUAL(ret_msg.message_type(), websocket_message_type::text_message);
            });

            websocket_outgoing_message msg;
            msg.set_utf8_message(body_str);
            client.send(msg).wait();

            receive_task.wait();
            client.close().wait();
        }
        catch (const websocket_exception& e)
        {
            if (is_timeout(e.what()))
            {
                // Since this test depends on an outside server sometimes it sporadically can fail due to timeouts
                // especially on our build machines.
                return;
            }
            throw;
        }

此处提供了更多指导您成功获取示例的示例 https://github.com/microsoft/cpprestsdk/wiki/Web-Socket