C++ 网络套接字库
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34423092/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
WebSocket Library
提问by thesys
I want to access a WebSocket API using C++ on Linux. I've seen different librarys (like libwebsocketsor websocketpp), but I'm not sure which I should use. The only thing I need to do is connect to the API and receive datato a string. So I'm looking for a very basicand simple solution, nothing too complex. Maybe someone has already made experience with a WebSocket library?
我想在 Linux 上使用 C++ 访问 WebSocket API。我见过不同的库(如libwebsockets或websocketpp),但我不确定应该使用哪个。我唯一需要做的就是连接到 API 并将数据接收为字符串。所以我正在寻找一个非常基本和简单的解决方案,没有什么太复杂的。也许有人已经使用过 WebSocket 库?
回答by Grigorii Chudnov
For a high-level API, you can use ws_client
from the cpprestlibrary {it wraps websocketpp}.
对于高层次的API,你可以使用ws_client
从cpprest库{它包装websocketpp}。
A sample application that runs against the echo server:
针对echo 服务器运行的示例应用程序:
#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;
}
Here .wait()
method is used to wait on tasks, however the code can be easily modified to do I/O in the asynchronous way.
这里的.wait()
方法用于等待任务,但是可以很容易地修改代码以异步方式进行 I/O。