首页 > 解决方案 > 如何使用 cpprestsdk 设置 websocket SSL 连接?

问题描述

我尝试使用 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握手失败”。

标签: sslwebsocket

解决方案


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

您还可以在此处获得 SSL 测试示例。我展示了一个使用 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


推荐阅读