如何从字符串创建一个web::uri以放入client.connect()

How can I create a web::uri from a string to put into client.connect()?

本文关键字:uri connect client web 创建 一个 字符串      更新时间:2023-10-16

client.connect(web::uri)是必需的,但在查看web::uri后,它不会接受字符串。api似乎说它可以接受一个字符串,但它不会,我不知道为什么。

#include <iostream>
#include <stdio.h>
#include <cpprest/ws_client.h>
using namespace std;
using namespace web;
using namespace web::websockets::client;
int main(int argc, char **args) {
    uri link = uri("ws://echo.websocket.org"); //PROBLEM LINE
    websocket_client client;    
    client.connect(link).wait(); 
    websocket_outgoing_message out_msg;
    out_msg.set_utf8_message("test");
    client.send(out_msg).wait();
    client.receive().then([](websocket_incoming_message in_msg) {
        return in_msg.extract_string();
    }).then([](string body) {
        cout << body << endl;
    }).wait();
    client.close().wait();
    return 0;
}

快速浏览一下uri的源代码就会发现有一个接受字符串参数的构造函数,但它不是一个简单明了的 C 类型字符串:

_ASYNCRTIMP uri(const utility::char_t *uri_string);

如果你在 windows 下构建它,你可能会发现 utility::char_t 实际上是wchar_t ,所以你可以在 URI 字符串前面加上 L 以将其标记为宽字符 unicode,如下所示:

uri link = uri(L"ws://echo.websocket.org");

我相信库提供了一个方便的跨平台字符串宏,U() .查看常见问题解答。我认为它的工作原理有点像这样:

uri link = uri(U("ws://echo.websocket.org"));