我想在 Linux 上使用 C++ 访问 WebSocket API。我见过不同的库(如 libwebsockets 或 websocketpp),但我不确定应该使用哪个。我唯一需要做的就是连接到 API 并接收数据到一个字符串。所以我正在寻找一个非常基本和简单的解决方案,不要太复杂。也许有人已经使用过 WebSocket 库?
最佳答案
对于高级 API,您可以使用 cpprest 中的 ws_client
图书馆{它包装websocketpp }。
针对 echo server 运行的示例应用程序:
#include <iostream>
#include <cpprest/ws_client.h>
using namespace std;
using namespace web;
using namespace web::websockets::client;
int main() {
websocket_client client;
client.connect("ws://echo.websocket.org").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; // test
}).wait();
client.close().wait();
return 0;
}
这里使用.wait()
方法来等待任务,但是代码可以很容易地修改为异步方式进行I/O。
关于c++ - WebSocket 库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34423092/