WebSocket Library [closed]

2019-03-11 08:18发布

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?

1条回答
SAY GOODBYE
2楼-- · 2019-03-11 08:39

For a high-level API, you can use ws_client from the cpprest library {it wraps websocketpp}.

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;
}

Here .wait() method is used to wait on tasks, however the code can be easily modified to do I/O in the asynchronous way.

查看更多
登录 后发表回答