【发布时间】:2016-03-29 03:29:37
【问题描述】:
我想在 Linux 上使用 C++ 访问 WebSocket API。我见过不同的库(如 libwebsockets 或 websocketpp),但我不确定应该使用哪个。我唯一需要做的就是连接到 API 并接收数据到一个字符串。所以我正在寻找一个非常基本和简单的解决方案,不要太复杂。也许有人已经使用过 WebSocket 库?
【问题讨论】:
我想在 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。
【讨论】: