WebSocket库

时间:2015-12-22 19:27:52

标签: c++ api websocket

我想在Linux上使用C ++访问WebSocket API。我看过不同的图书馆(比如 libwebsockets websocketpp ),但我不确定应该使用哪个。我唯一需要做的就是连接到API并接收数据到字符串。所以,我正在寻找一个非常基本和简单的解决方案,没有什么太复杂的。也许有人已经获得了WebSocket库的经验?

1 个答案:

答案 0 :(得分:16)

对于高级API,您可以使用cpprest库{{wrap} websocketpp}中的ws_client

针对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.