网络套接字库 [英] WebSocket Library
问题描述
我想在 Linux 上使用 C++ 访问 WebSocket API.我见过不同的库(例如 libwebsockets 或 websocketpp),但我不确定应该使用哪个.我唯一需要做的就是连接到 API 并接收数据到一个字符串.所以我正在寻找一个非常基本和简单的解决方案,没有什么太复杂的.也许有人已经使用过 WebSocket 库?
I want to access a WebSocket API using C++ on Linux. I've seen different librarys (like libwebsockets or websocketpp), but I'm not sure which I should use. The only thing I need to do is connect to the API and receive data to a string. So I'm looking for a very basic and simple solution, nothing too complex. Maybe someone has already made experience with a WebSocket library?
推荐答案
对于高级 API,您可以使用 cpprest 库{它包装了 websocketpp}.
For a high-level API, you can use ws_client
from the cpprest library {it wraps websocketpp}.
针对 echo 服务器 运行的示例应用程序:
A sample application that runs against the 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.
Here .wait()
method is used to wait on tasks, however the code can be easily modified to do I/O in the asynchronous way.
这篇关于网络套接字库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!