Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WebSocket Library [closed]

Tags:

c++

websocket

api

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?

like image 642
Bobface Avatar asked Dec 22 '15 19:12

Bobface


People also ask

What does WebSocket closed mean?

The WebSocket is closed before the connection is established error message indicates that some client code, or other mechanism, has closed the websocket connection before the connection was fully established.

What causes Websockets to close?

By default, if a ping has not been received in 60 seconds, and the connection has been otherwise inactive, the platform will close the WebSocket. This timeout is configurable in the WS Communication Subsystem configuration, Idle Connection Timeout (sec) parameter.

Can I reopen a closed WebSocket?

Once the original connection has been closed, you need to create a new websocket object with new event listeners: var SERVER = 'ws://localhost:8080' var ws = new WebSocket(SERVER) ws.

How do you know if a WebSocket is closed?

You can check if a WebSocket is disconnected by doing either of the following: Specifying a function to the WebSocket. onclose event handler property, or; Using addEventListener to listen to the close event.


1 Answers

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.

like image 118
Grigorii Chudnov Avatar answered Oct 11 '22 14:10

Grigorii Chudnov