Debian Codegraph @

LspCpp/third_party/ixwebsocket/docs/usage.md

raw
1 # Examples
2
3 The [*ws*](https://github.com/machinezone/IXWebSocket/tree/master/ws) folder countains many interactive programs for chat, [file transfers](https://github.com/machinezone/IXWebSocket/blob/master/ws/ws_send.cpp), [curl like](https://github.com/machinezone/IXWebSocket/blob/master/ws/ws_http_client.cpp) http clients, demonstrating client and server usage.
4
5 ## Windows note
6
7 To use the network system on Windows, you need to initialize it once with *WSAStartup()* and clean it up with *WSACleanup()*. We have helpers for that which you can use, see below. This init would typically take place in your main function.
8
9 ```cpp
10 #include <ixwebsocket/IXNetSystem.h>
11
12 int main()
13 {
14 ix::initNetSystem();
15
16 ...
17
18 ix::uninitNetSystem();
19 return 0;
20 }
21 ```
22
23 ## WebSocket client API
24
25 ```cpp
26 #include <ixwebsocket/IXWebSocket.h>
27
28 ...
29
30 // Our websocket object
31 ix::WebSocket webSocket;
32
33 std::string url("ws://localhost:8080/");
34 webSocket.setUrl(url);
35
36 // Optional heart beat, sent every 45 seconds when there is not any traffic
37 // to make sure that load balancers do not kill an idle connection.
38 webSocket.setPingInterval(45);
39
40 // Per message deflate connection is not enabled by default. You can tweak its parameters, enable or disable it with
41 webSocket.enablePerMessageDeflate();
42 webSocket.disablePerMessageDeflate();
43
44 // Setup a callback to be fired when a message or an event (open, close, error) is received
45 webSocket.setOnMessageCallback([](const ix::WebSocketMessagePtr& msg)
46 {
47 if (msg->type == ix::WebSocketMessageType::Message)
48 {
49 std::cout << msg->str << std::endl;
50 }
51 }
52 );
53
54 // Now that our callback is setup, we can start our background thread and receive messages
55 webSocket.start();
56
57 // Send a message to the server (default to TEXT mode)
58 webSocket.send("hello world");
59
60 // The message can be sent in BINARY mode (useful if you send MsgPack data for example)
61 webSocket.sendBinary("some serialized binary data");
62
63 // ... finally ...
64
65 // Stop the connection
66 webSocket.stop()
67 ```
68
69 ### Sending messages
70
71 `WebSocketSendInfo result = websocket.send("foo")` will send a message.
72
73 If the connection was closed, sending will fail, and the success field of the result object will be set to false. There could also be a compression error in which case the compressError field will be set to true. The payloadSize field and wireSize fields will tell you respectively how much bytes the message weight, and how many bytes were sent on the wire (potentially compressed + counting the message header (a few bytes).
74
75 There is an optional progress callback that can be passed in as the second argument. If a message is large it will be fragmented into chunks which will be sent independantly. Everytime the we can write a fragment into the OS network cache, the callback will be invoked. If a user wants to cancel a slow send, false should be returned from within the callback.
76
77 Here is an example code snippet copied from the ws send sub-command. Each fragment weights 32K, so the total integer is the wireSize divided by 32K. As an example if you are sending 32M of data, uncompressed, total will be 1000. current will be set to 0 for the first fragment, then 1, 2 etc...
78
79 ```
80 auto result =
81 _webSocket.sendBinary(serializedMsg, [this, throttle](int current, int total) -> bool {
82 spdlog::info("ws_send: Step {} out of {}", current + 1, total);
83
84 if (throttle)
85 {
86 std::chrono::duration<double, std::milli> duration(10);
87 std::this_thread::sleep_for(duration);
88 }
89
90 return _connected;
91 });
92 ```
93
94 The `send()` and `sendText()` methods check that the string contains only valid UTF-8 characters. If you know that the string is a valid UTF-8 string you can skip that step and use the `sendUtf8Text` method instead.
95
96 With the IXWebSocketSendData overloads of `sendUtf8Text` and `sendBinary` it is possible to not only send std::string but also `std::vector<char>`, `std::vector<uint8_t>` and `char*`.
97
98 ```
99 std::vector<uint8_t> data({1, 2, 3, 4});
100 auto result = webSocket.sendBinary(data);
101
102 const char* text = "Hello World!";
103 result = webSocket.sendUtf8Text(IXWebSocketSendData(text, strlen(text)));
104 ```
105
106 ### ReadyState
107
108 `getReadyState()` returns the state of the connection. There are 4 possible states.
109
110 1. ReadyState::Connecting - The connection is not yet open.
111 2. ReadyState::Open - The connection is open and ready to communicate.
112 3. ReadyState::Closing - The connection is in the process of closing.
113 4. ReadyState::Closed - The connection is closed or could not be opened.
114
115 ### Open and Close notifications
116
117 The onMessage event will be fired when the connection is opened or closed. This is similar to the [JavaScript browser API](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket), which has `open` and `close` events notification that can be registered with the browser `addEventListener`.
118
119 ```cpp
120 webSocket.setOnMessageCallback([](const ix::WebSocketMessagePtr& msg)
121 {
122 if (msg->type == ix::WebSocketMessageType::Open)
123 {
124 std::cout << "send greetings" << std::endl;
125
126 // Headers can be inspected (pairs of string/string)
127 std::cout << "Handshake Headers:" << std::endl;
128 for (auto it : msg->headers)
129 {
130 std::cout << it.first << ": " << it.second << std::endl;
131 }
132 }
133 else if (msg->type == ix::WebSocketMessageType::Close)
134 {
135 std::cout << "disconnected" << std::endl;
136
137 // The server can send an explicit code and reason for closing.
138 // This data can be accessed through the closeInfo object.
139 std::cout << msg->closeInfo.code << std::endl;
140 std::cout << msg->closeInfo.reason << std::endl;
141 }
142 }
143 );
144 ```
145
146 ### Error notification
147
148 A message will be fired when there is an error with the connection. The message type will be `ix::WebSocketMessageType::Error`. Multiple fields will be available on the event to describe the error.
149
150 ```cpp
151 webSocket.setOnMessageCallback([](const ix::WebSocketMessagePtr& msg)
152 {
153 if (msg->type == ix::WebSocketMessageType::Error)
154 {
155 std::stringstream ss;
156 ss << "Error: " << msg->errorInfo.reason << std::endl;
157 ss << "#retries: " << msg->errorInfo.retries << std::endl;
158 ss << "Wait time(ms): " << msg->errorInfo.wait_time << std::endl;
159 ss << "HTTP Status: " << msg->errorInfo.http_status << std::endl;
160 std::cout << ss.str() << std::endl;
161 }
162 }
163 );
164 ```
165
166 ### start, stop
167
168 1. `websocket.start()` connect to the remote server and starts the message receiving background thread.
169 2. `websocket.stop()` disconnect from the remote server and closes the background thread.
170
171 ### Configuring the remote url
172
173 The url can be set and queried after a websocket object has been created. You will have to call `stop` and `start` if you want to disconnect and connect to that new url.
174
175 ```cpp
176 std::string url("wss://example.com");
177 websocket.configure(url);
178 ```
179
180 ### Ping/Pong support
181
182 Ping/pong messages are used to implement keep-alive. 2 message types exists to identify ping and pong messages. Note that when a ping message is received, a pong is instantly send back as requested by the WebSocket spec.
183
184 ```cpp
185 webSocket.setOnMessageCallback([](const ix::WebSocketMessagePtr& msg)
186 {
187 if (msg->type == ix::WebSocketMessageType::Ping ||
188 msg->type == ix::WebSocketMessageType::Pong)
189 {
190 std::cout << "pong data: " << msg->str << std::endl;
191 }
192 }
193 );
194 ```
195
196 A ping message can be sent to the server, with an optional data string.
197
198 ```cpp
199 websocket.ping("ping data, optional (empty string is ok): limited to 125 bytes long");
200 ```
201
202 ### Heartbeat.
203
204 You can configure an optional heart beat / keep-alive, sent every 45 seconds
205 when there is no any traffic to make sure that load balancers do not kill an
206 idle connection.
207
208 ```cpp
209 webSocket.setPingInterval(45);
210 ```
211
212 ### Supply extra HTTP headers.
213
214 You can set extra HTTP headers to be sent during the WebSocket handshake.
215
216 ```cpp
217 WebSocketHttpHeaders headers;
218 headers["foo"] = "bar";
219 webSocket.setExtraHeaders(headers);
220 ```
221
222 ### Subprotocols
223
224 You can specify subprotocols to be set during the WebSocket handshake. For more info you can refer to [this doc](https://hpbn.co/websocket/#subprotocol-negotiation).
225
226 ```cpp
227 webSocket.addSubprotocol("appProtocol-v1");
228 webSocket.addSubprotocol("appProtocol-v2");
229 ```
230
231 The protocol that the server did accept is available in the open info `protocol` field.
232
233 ```cpp
234 std::cout << "protocol: " << msg->openInfo.protocol << std::endl;
235 ```
236
237 ### Automatic reconnection
238
239 Automatic reconnection kicks in when the connection is disconnected without the user consent. This feature is on by default and can be turned off.
240
241 ```cpp
242 webSocket.enableAutomaticReconnection(); // turn on
243 webSocket.disableAutomaticReconnection(); // turn off
244 bool enabled = webSocket.isAutomaticReconnectionEnabled(); // query state
245 ```
246
247 The technique to calculate wait time is called [exponential
248 backoff](https://docs.aws.amazon.com/general/latest/gr/api-retries.html). Here
249 are the default waiting times between attempts (from connecting with `ws connect ws://foo.com`)
250
251 ```
252 > Connection error: Got bad status connecting to foo.com, status: 301, HTTP Status line: HTTP/1.1 301 Moved Permanently
253
254 #retries: 1
255 Wait time(ms): 100
256 #retries: 2
257 Wait time(ms): 200
258 #retries: 3
259 Wait time(ms): 400
260 #retries: 4
261 Wait time(ms): 800
262 #retries: 5
263 Wait time(ms): 1600
264 #retries: 6
265 Wait time(ms): 3200
266 #retries: 7
267 Wait time(ms): 6400
268 #retries: 8
269 Wait time(ms): 10000
270 ```
271
272 The waiting time is capped by default at 10s between 2 attempts, but that value
273 can be changed and queried. The minimum waiting time can also be set.
274
275 ```cpp
276 webSocket.setMaxWaitBetweenReconnectionRetries(5 * 1000); // 5000ms = 5s
277 uint32_t m = webSocket.getMaxWaitBetweenReconnectionRetries();
278
279 webSocket.setMinWaitBetweenReconnectionRetries(1000); // 1000ms = 1s
280 uint32_t m = webSocket.getMinWaitBetweenReconnectionRetries();
281 ```
282
283 ## Handshake timeout
284
285 You can control how long to wait until timing out while waiting for the websocket handshake to be performed.
286
287 ```
288 int handshakeTimeoutSecs = 1;
289 setHandshakeTimeout(handshakeTimeoutSecs);
290 ```
291
292 ## WebSocket server API
293
294 ### Legacy api
295
296 This api was actually changed to take a weak_ptr<WebSocket> as the first argument to setOnConnectionCallback ; previously it would take a shared_ptr<WebSocket> which was creating cycles and then memory leaks problems.
297
298 ```cpp
299 #include <ixwebsocket/IXWebSocketServer.h>
300
301 ...
302
303 // Run a server on localhost at a given port.
304 // Bound host name, max connections and listen backlog can also be passed in as parameters.
305 int port = 8008;
306 std::string host("127.0.0.1"); // If you need this server to be accessible on a different machine, use "0.0.0.0"
307 ix::WebSocketServer server(port, host);
308
309 server.setOnConnectionCallback(
310 [&server](std::weak_ptr<WebSocket> webSocket,
311 std::shared_ptr<ConnectionState> connectionState)
312 {
313 std::cout << "Remote ip: " << connectionState->remoteIp << std::endl;
314
315 auto ws = webSocket.lock();
316 if (ws)
317 {
318 ws->setOnMessageCallback(
319 [webSocket, connectionState, &server](const ix::WebSocketMessagePtr msg)
320 {
321 if (msg->type == ix::WebSocketMessageType::Open)
322 {
323 std::cout << "New connection" << std::endl;
324
325 // A connection state object is available, and has a default id
326 // You can subclass ConnectionState and pass an alternate factory
327 // to override it. It is useful if you want to store custom
328 // attributes per connection (authenticated bool flag, attributes, etc...)
329 std::cout << "id: " << connectionState->getId() << std::endl;
330
331 // The uri the client did connect to.
332 std::cout << "Uri: " << msg->openInfo.uri << std::endl;
333
334 std::cout << "Headers:" << std::endl;
335 for (auto it : msg->openInfo.headers)
336 {
337 std::cout << it.first << ": " << it.second << std::endl;
338 }
339 }
340 else if (msg->type == ix::WebSocketMessageType::Message)
341 {
342 // For an echo server, we just send back to the client whatever was received by the server
343 // All connected clients are available in an std::set. See the broadcast cpp example.
344 // Second parameter tells whether we are sending the message in binary or text mode.
345 // Here we send it in the same mode as it was received.
346 auto ws = webSocket.lock();
347 if (ws)
348 {
349 ws->send(msg->str, msg->binary);
350 }
351 }
352 }
353 }
354 );
355 }
356 );
357
358 auto res = server.listen();
359 if (!res.first)
360 {
361 // Error handling
362 return 1;
363 }
364
365 // Per message deflate connection is enabled by default. It can be disabled
366 // which might be helpful when running on low power devices such as a Rasbery Pi
367 server.disablePerMessageDeflate();
368
369 // Run the server in the background. Server can be stoped by calling server.stop()
370 server.start();
371
372 // Block until server.stop() is called.
373 server.wait();
374
375 ```
376
377 ### New api
378
379 The new API does not require to use 2 nested callbacks, which is a bit annoying. The real fix is that there was a memory leak due to a shared_ptr cycle, due to passing down a shared_ptr<WebSocket> down to the callbacks.
380
381 The webSocket reference is guaranteed to be always valid ; by design the callback will never be invoked with a null webSocket object.
382
383 ```cpp
384 #include <ixwebsocket/IXWebSocketServer.h>
385
386 ...
387
388 // Run a server on localhost at a given port.
389 // Bound host name, max connections and listen backlog can also be passed in as parameters.
390 int port = 8008;
391 std::string host("127.0.0.1"); // If you need this server to be accessible on a different machine, use "0.0.0.0"
392 ix::WebSocketServer server(port, host);
393
394 server.setOnClientMessageCallback([](std::shared_ptr<ix::ConnectionState> connectionState, ix::WebSocket & webSocket, const ix::WebSocketMessagePtr & msg) {
395 // The ConnectionState object contains information about the connection,
396 // at this point only the client ip address and the port.
397 std::cout << "Remote ip: " << connectionState->getRemoteIp() << std::endl;
398
399 if (msg->type == ix::WebSocketMessageType::Open)
400 {
401 std::cout << "New connection" << std::endl;
402
403 // A connection state object is available, and has a default id
404 // You can subclass ConnectionState and pass an alternate factory
405 // to override it. It is useful if you want to store custom
406 // attributes per connection (authenticated bool flag, attributes, etc...)
407 std::cout << "id: " << connectionState->getId() << std::endl;
408
409 // The uri the client did connect to.
410 std::cout << "Uri: " << msg->openInfo.uri << std::endl;
411
412 std::cout << "Headers:" << std::endl;
413 for (auto it : msg->openInfo.headers)
414 {
415 std::cout << "\t" << it.first << ": " << it.second << std::endl;
416 }
417 }
418 else if (msg->type == ix::WebSocketMessageType::Message)
419 {
420 // For an echo server, we just send back to the client whatever was received by the server
421 // All connected clients are available in an std::set. See the broadcast cpp example.
422 // Second parameter tells whether we are sending the message in binary or text mode.
423 // Here we send it in the same mode as it was received.
424 std::cout << "Received: " << msg->str << std::endl;
425
426 webSocket.send(msg->str, msg->binary);
427 }
428 });
429
430 auto res = server.listen();
431 if (!res.first)
432 {
433 // Error handling
434 return 1;
435 }
436
437 // Per message deflate connection is enabled by default. It can be disabled
438 // which might be helpful when running on low power devices such as a Rasbery Pi
439 server.disablePerMessageDeflate();
440
441 // Run the server in the background. Server can be stoped by calling server.stop()
442 server.start();
443
444 // Block until server.stop() is called.
445 server.wait();
446
447 ```
448
449 ### Heartbeat
450
451 You can configure an optional heartbeat / keep-alive for the WebSocket server. The heartbeat interval can be adjusted or disabled when constructing the `WebSocketServer`. Setting the interval to `-1` disables the heartbeat feature; this is the default setting. The parameter you set will be applied to every `WebSocket` object that the server creates.
452
453 To enable a 45 second heartbeat on a `WebSocketServer`:
454
455 ```cpp
456 int pingIntervalSeconds = 45;
457 ix::WebSocketServer server(port, host, backlog, maxConnections, handshakeTimeoutSecs, addressFamily, pingIntervalSeconds);
458 ```
459
460 ## HTTP client API
461
462 ```cpp
463 #include <ixwebsocket/IXHttpClient.h>
464
465 ...
466
467 //
468 // Preparation
469 //
470 HttpClient httpClient;
471 HttpRequestArgsPtr args = httpClient.createRequest();
472
473 // Custom headers can be set
474 WebSocketHttpHeaders headers;
475 headers["Foo"] = "bar";
476 args->extraHeaders = headers;
477
478 // Timeout options
479 args->connectTimeout = connectTimeout;
480 args->transferTimeout = transferTimeout;
481
482 // Redirect options
483 args->followRedirects = followRedirects;
484 args->maxRedirects = maxRedirects;
485
486 // Misc
487 args->compress = compress; // Enable gzip compression
488 args->verbose = verbose;
489 args->logger = [](const std::string& msg)
490 {
491 std::cout << msg;
492 };
493
494 //
495 // Synchronous Request
496 //
497 HttpResponsePtr out;
498 std::string url = "https://www.google.com";
499
500 // HEAD request
501 out = httpClient.head(url, args);
502
503 // GET request
504 out = httpClient.get(url, args);
505
506 // POST request with parameters
507 HttpParameters httpParameters;
508 httpParameters["foo"] = "bar";
509
510 // HTTP form data can be passed in as well, for multi-part upload of files
511 HttpFormDataParameters httpFormDataParameters;
512 httpParameters["baz"] = "booz";
513
514 out = httpClient.post(url, httpParameters, httpFormDataParameters, args);
515
516 // POST request with a body
517 out = httpClient.post(url, std::string("foo=bar"), args);
518
519 // PUT and PATCH are available too.
520
521 //
522 // Result
523 //
524 auto statusCode = response->statusCode; // Can be HttpErrorCode::Ok, HttpErrorCode::UrlMalformed, etc...
525 auto errorCode = response->errorCode; // 200, 404, etc...
526 auto responseHeaders = response->headers; // All the headers in a special case-insensitive unordered_map of (string, string)
527 auto body = response->body; // All the bytes from the response as an std::string
528 auto errorMsg = response->errorMsg; // Descriptive error message in case of failure
529 auto uploadSize = response->uploadSize; // Byte count of uploaded data
530 auto downloadSize = response->downloadSize; // Byte count of downloaded data
531
532 //
533 // Asynchronous Request
534 //
535 bool async = true;
536 HttpClient httpClient(async);
537 auto args = httpClient.createRequest(url, HttpClient::kGet);
538
539 // If you define a chunk callback it will be called repeteadly with the
540 // incoming data. This allows to process data on the go or write it to disk
541 // instead of accumulating the data in memory.
542 args.onChunkCallback = [](const std::string& data)
543 {
544 // process data
545 };
546
547 // Push the request to a queue,
548 bool ok = httpClient.performRequest(args, [](const HttpResponsePtr& response)
549 {
550 // This callback execute in a background thread. Make sure you uses appropriate protection such as mutex
551 auto statusCode = response->statusCode; // acess results
552
553 // response->body is empty if onChunkCallback was used
554 }
555 );
556
557 // ok will be false if your httpClient is not async
558
559 // A request in progress can be cancelled by setting the cancel flag. It does nothing if the request already completed.
560 args->cancel = true;
561 ```
562
563 See this [issue](https://github.com/machinezone/IXWebSocket/issues/209) for links about uploading files with HTTP multipart.
564
565 ## HTTP server API
566
567 ```cpp
568 #include <ixwebsocket/IXHttpServer.h>
569
570 ix::HttpServer server(port, hostname);
571
572 auto res = server.listen();
573 if (!res.first)
574 {
575 std::cerr << res.second << std::endl;
576 return 1;
577 }
578
579 server.start();
580 server.wait();
581 ```
582
583 If you want to handle how requests are processed, implement the setOnConnectionCallback callback, which takes an HttpRequestPtr as input, and returns an HttpResponsePtr. You can look at HttpServer::setDefaultConnectionCallback for a slightly more advanced callback example.
584
585 ```cpp
586 setOnConnectionCallback(
587 [this](HttpRequestPtr request,
588 std::shared_ptr<ConnectionState> connectionState) -> HttpResponsePtr
589 {
590 // Build a string for the response
591 std::stringstream ss;
592 ss << connectionState->getRemoteIp();
593 << " "
594 << request->method
595 << " "
596 << request->uri;
597
598 std::string content = ss.str();
599
600 return std::make_shared<HttpResponse>(200, "OK",
601 HttpErrorCode::Ok,
602 WebSocketHttpHeaders(),
603 content);
604 }
605 ```
606
607 ## TLS support and configuration
608
609 To leverage TLS features, the library must be compiled with the option `USE_TLS=1`.
610
611 If you are using OpenSSL, try to be on a version higher than 1.1.x as there there are thread safety problems with 1.0.x.
612
613 Then, secure sockets are automatically used when connecting to a `wss://*` url.
614
615 Additional TLS options can be configured by passing a `ix::SocketTLSOptions` instance to the
616 `setTLSOptions` on `ix::WebSocket` (or `ix::WebSocketServer` or `ix::HttpServer`)
617
618 ```cpp
619 webSocket.setTLSOptions({
620 .certFile = "path/to/cert/file.pem",
621 .keyFile = "path/to/key/file.pem",
622 .caFile = "path/to/trust/bundle/file.pem", // as a file, or in memory buffer in PEM format
623 .tls = true // required in server mode
624 });
625 ```
626
627 Specifying `certFile` and `keyFile` configures the certificate that will be used to communicate with TLS peers.
628
629 On a client, this is only necessary for connecting to servers that require a client certificate.
630
631 On a server, this is necessary for TLS support.
632
633 Specifying `caFile` configures the trusted roots bundle file (in PEM format) that will be used to verify peer certificates.
634 - The special value of `SYSTEM` (the default) indicates that the system-configured trust bundle should be used; this is generally what you want when connecting to any publicly exposed API/server.
635 - The special value of `NONE` can be used to disable peer verification; this is only recommended to rule out certificate verification when testing connectivity.
636 - If the value contain the special value `-----BEGIN CERTIFICATE-----`, the value will be read from memory, and not from a file. This is convenient on platforms like Android where reading / writing to the file system can be challenging without proper permissions, or without knowing the location of a temp directory.
637
638 For a client, specifying `caFile` can be used if connecting to a server that uses a self-signed cert, or when using a custom CA in an internal environment.
639
640 For a server, specifying `caFile` implies that:
641 1. You require clients to present a certificate
642 1. It must be signed by one of the trusted roots in the file
643
644 By default, a destination's hostname is always validated against the certificate that it presents. To accept certificates with any hostname, set `ix::SocketTLSOptions::disable_hostname_validation` to `true`.