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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With