【问题标题】:How to setup websocket SSL connect using cpprestsdk?如何使用 cpprestsdk 设置 websocket SSL 连接?
【发布时间】:2019-07-04 09:37:06
【问题描述】:

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

【问题讨论】:

    标签: ssl websocket


    【解决方案1】:

    可在此处找到 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

    【讨论】:

    • 请注意,websocket.org 服务已停止,因此在尝试连接时复制和粘贴示例代码会引发错误。
    猜你喜欢
    • 1970-01-01
    • 2015-09-03
    • 1970-01-01
    • 1970-01-01
    • 2012-07-30
    • 1970-01-01
    • 2015-08-26
    • 1970-01-01
    • 2016-07-16
    相关资源
    最近更新 更多