### Initialize and Start an HTTP Server Source: https://machinezone.github.io/IXWebSocket/usage Basic setup for starting an IXHttpServer instance. ```cpp #include ix::HttpServer server(port, hostname); auto res = server.listen(); if (!res.first) { std::cerr << res.second << std::endl; return 1; } server.start(); server.wait(); ``` -------------------------------- ### Basic WebSocket Client Setup and Usage Source: https://machinezone.github.io/IXWebSocket/usage Sets up a WebSocket client, configures URL, ping interval, and message callback. Starts the client in a background thread to receive messages and demonstrates sending text and binary messages. ```cpp #include ... // Our websocket object ix::WebSocket webSocket; std::string url("ws://localhost:8080/"); webSocket.setUrl(url); // Optional heart beat, sent every 45 seconds when there is not any traffic // to make sure that load balancers do not kill an idle connection. webSocket.setPingInterval(45); // Per message deflate connection is not enabled by default. You can tweak its parameters, enable or disable it with webSocket.enablePerMessageDeflate(); webSocket.disablePerMessageDeflate(); // Setup a callback to be fired when a message or an event (open, close, error) is received webSocket.setOnMessageCallback([](const ix::WebSocketMessagePtr& msg) { if (msg->type == ix::WebSocketMessageType::Message) { std::cout << msg->str << std::endl; } } ); // Now that our callback is setup, we can start our background thread and receive messages webSocket.start(); // Send a message to the server (default to TEXT mode) webSocket.send("hello world"); // The message can be sent in BINARY mode (useful if you send MsgPack data for example) webSocket.sendBinary("some serialized binary data"); // ... finally ... // Stop the connection webSocket.stop() ``` -------------------------------- ### Install via vcpkg Source: https://machinezone.github.io/IXWebSocket/build Command to install the library using the vcpkg package manager. ```bash vcpkg install ixwebsocket ``` -------------------------------- ### Start push server Source: https://machinezone.github.io/IXWebSocket/performance Initiates a server that sends a specified message in a loop to connected clients. ```bash ws push_server -q --send_msg 'yo' ``` -------------------------------- ### Run proxy with configuration file Source: https://machinezone.github.io/IXWebSocket/ws Starts the proxy server using a specific configuration file and port. ```bash ws proxy_server --config_path proxyConfig.json --port 8765 ``` -------------------------------- ### Implement a WebSocket client in C++ Source: https://machinezone.github.io/IXWebSocket A standalone example demonstrating how to initialize the network system, connect to a WebSocket server, and handle messages via callbacks. ```cpp /* * main.cpp * Author: Benjamin Sergeant * Copyright (c) 2020 Machine Zone, Inc. All rights reserved. * * Super simple standalone example. See ws folder, unittest and doc/usage.md for more. * * On macOS * $ mkdir -p build ; (cd build ; cmake -DUSE_TLS=1 .. ; make -j ; make install) * $ clang++ --std=c++11 --stdlib=libc++ main.cpp -lixwebsocket -lz -framework Security -framework Foundation * $ ./a.out * * Or use cmake -DBUILD_DEMO=ON option for other platforms */ #include #include #include #include int main() { // Required on Windows ix::initNetSystem(); // Our websocket object ix::WebSocket webSocket; // Connect to a server with encryption // See https://machinezone.github.io/IXWebSocket/usage/#tls-support-and-configuration std::string url("wss://echo.websocket.org"); webSocket.setUrl(url); std::cout << "Connecting to " << url << "..." << std::endl; // Setup a callback to be fired (in a background thread, watch out for race conditions !) // when a message or an event (open, close, error) is received webSocket.setOnMessageCallback([](const ix::WebSocketMessagePtr& msg) { if (msg->type == ix::WebSocketMessageType::Message) { std::cout << "received message: " << msg->str << std::endl; std::cout << "> " << std::flush; } else if (msg->type == ix::WebSocketMessageType::Open) { std::cout << "Connection established" << std::endl; std::cout << "> " << std::flush; } else if (msg->type == ix::WebSocketMessageType::Error) { // Maybe SSL is not configured properly std::cout << "Connection error: " << msg->errorInfo.reason << std::endl; std::cout << "> " << std::flush; } } ); // Now that our callback is setup, we can start our background thread and receive messages webSocket.start(); // Send a message to the server (default to TEXT mode) webSocket.send("hello world"); // Display a prompt std::cout << "> " << std::flush; std::string text; // Read text from the console and send messages in text mode. // Exit with Ctrl-D on Unix or Ctrl-Z on Windows. while (std::getline(std::cin, text)) { webSocket.send(text); std::cout << "> " << std::flush; } return 0; } ``` -------------------------------- ### Run a WebSocket Server Source: https://machinezone.github.io/IXWebSocket/usage This snippet demonstrates how to set up and run a basic WebSocket server using IXWebSocket. It includes setting up the server, defining a message callback for handling client connections and messages, and starting the server. Ensure the port and host are correctly configured for your environment. ```cpp #include ... // Run a server on localhost at a given port. // Bound host name, max connections and listen backlog can also be passed in as parameters. int port = 8008; std::string host("127.0.0.1"); // If you need this server to be accessible on a different machine, use "0.0.0.0" ix::WebSocketServer server(port, host); server.setOnClientMessageCallback([](std::shared_ptr connectionState, ix::WebSocket & webSocket, const ix::WebSocketMessagePtr & msg) { // The ConnectionState object contains information about the connection, // at this point only the client ip address and the port. std::cout << "Remote ip: " << connectionState->getRemoteIp() << std::endl; if (msg->type == ix::WebSocketMessageType::Open) { std::cout << "New connection" << std::endl; // A connection state object is available, and has a default id // You can subclass ConnectionState and pass an alternate factory // to override it. It is useful if you want to store custom // attributes per connection (authenticated bool flag, attributes, etc...) std::cout << "id: " << connectionState->getId() << std::endl; // The uri the client did connect to. std::cout << "Uri: " << msg->openInfo.uri << std::endl; std::cout << "Headers:" << std::endl; for (auto it : msg->openInfo.headers) { std::cout << "\t" << it.first << ": " << it.second << std::endl; } } else if (msg->type == ix::WebSocketMessageType::Message) { // For an echo server, we just send back to the client whatever was received by the server // All connected clients are available in an std::set. See the broadcast cpp example. // Second parameter tells whether we are sending the message in binary or text mode. // Here we send it in the same mode as it was received. std::cout << "Received: " << msg->str << std::endl; webSocket.send(msg->str, msg->binary); } }); auto res = server.listen(); if (!res.first) { // Error handling return 1; } // Per message deflate connection is enabled by default. It can be disabled // which might be helpful when running on low power devices such as a Rasbery Pi server.disablePerMessageDeflate(); // Run the server in the background. Server can be stoped by calling server.stop() server.start(); // Block until server.stop() is called. server.wait(); ``` -------------------------------- ### Run a basic WebSocket proxy Source: https://machinezone.github.io/IXWebSocket/ws Starts a proxy server that forwards traffic from a local port to a remote host. ```bash ws proxy_server --remote_host ws://127.0.0.1:9000 -v Listening on 127.0.0.1:8008 ``` -------------------------------- ### Perform file transfer Source: https://machinezone.github.io/IXWebSocket/ws Commands to set up a transfer server, start a receiver, and send a file. ```bash # Start transfer server, which is just a broadcast server at this point ws transfer # running on port 8080. # Start receiver first ws receive ws://localhost:8080 # Then send a file. File will be received and written to disk by the receiver process ws send ws://localhost:8080 /file/to/path ``` -------------------------------- ### Connect to WebSocket with Ping Interval Source: https://machinezone.github.io/IXWebSocket/CHANGELOG Example of using the ws connect command with a specified ping interval. ```bash IXWebSocket$ ws connect --ping_interval 2 wss://echo.websocket.org Type Ctrl-D to exit prompt... Connecting to url: wss://echo.websocket.org > ws_connect: connected [2020-03-17 23:53:02.726] [info] Uri: / [2020-03-17 23:53:02.726] [info] Headers: [2020-03-17 23:53:02.727] [info] Connection: Upgrade [2020-03-17 23:53:02.727] [info] Date: Wed, 18 Mar 2020 06:45:05 GMT [2020-03-17 23:53:02.727] [info] Sec-WebSocket-Accept: 0gtqbxW0aVL/QI/ICpLFnRaiKgA= [2020-03-17 23:53:02.727] [info] sec-websocket-extensions: [2020-03-17 23:53:02.727] [info] Server: Kaazing Gateway [2020-03-17 23:53:02.727] [info] Upgrade: websocket [2020-03-17 23:53:04.894] [info] Received pong [2020-03-17 23:53:06.859] [info] Received pong [2020-03-17 23:53:08.881] [info] Received pong [2020-03-17 23:53:10.848] [info] Received pong [2020-03-17 23:53:12.898] [info] Received pong [2020-03-17 23:53:14.865] [info] Received pong [2020-03-17 23:53:16.890] [info] Received pong [2020-03-17 23:53:18.853] [info] Received pong [2020-03-17 23:53:19.388] [info] ws_connect: connection closed: code 1000 reason Normal closure [2020-03-17 23:53:19.502] [info] Received 208 bytes [2020-03-17 23:53:19.502] [info] Sent 0 bytes ``` -------------------------------- ### Include IXWebSocket via ExternalProject_Add Source: https://machinezone.github.io/IXWebSocket/build Example of fetching the project externally during the build process. ```cmake ExternalProject_Add( IXWebSocket GIT_REPOSITORY https://github.com/machinezone/IXWebSocket.git ... ) ``` -------------------------------- ### Perform HTTP Requests with IXHttpClient Source: https://machinezone.github.io/IXWebSocket/usage Demonstrates configuring request arguments, performing synchronous HEAD, GET, and POST requests, and accessing response details. ```cpp #include ... // // Preparation // HttpClient httpClient; HttpRequestArgsPtr args = httpClient.createRequest(); // Custom headers can be set WebSocketHttpHeaders headers; headers["Foo"] = "bar"; args->extraHeaders = headers; // Timeout options args->connectTimeout = connectTimeout; args->transferTimeout = transferTimeout; // Redirect options args->followRedirects = followRedirects; args->maxRedirects = maxRedirects; // Misc args->compress = compress; // Enable gzip compression args->verbose = verbose; args->logger = [](const std::string& msg) { std::cout << msg; }; // // Synchronous Request // HttpResponsePtr out; std::string url = "https://www.google.com"; // HEAD request out = httpClient.head(url, args); // GET request out = httpClient.get(url, args); // POST request with parameters HttpParameters httpParameters; httpParameters["foo"] = "bar"; // HTTP form data can be passed in as well, for multi-part upload of files HttpFormDataParameters httpFormDataParameters; httpParameters["baz"] = "booz"; out = httpClient.post(url, httpParameters, httpFormDataParameters, args); // POST request with a body out = httpClient.post(url, std::string("foo=bar"), args); // PUT and PATCH are available too. // // Result // auto statusCode = response->statusCode; // Can be HttpErrorCode::Ok, HttpErrorCode::UrlMalformed, etc... auto errorCode = response->errorCode; // 200, 404, etc... auto responseHeaders = response->headers; // All the headers in a special case-insensitive unordered_map of (string, string) auto body = response->body; // All the bytes from the response as an std::string auto errorMsg = response->errorMsg; // Descriptive error message in case of failure auto uploadSize = response->uploadSize; // Byte count of uploaded data auto downloadSize = response->downloadSize; // Byte count of downloaded data ``` -------------------------------- ### Run Echo Server with Authorization Source: https://machinezone.github.io/IXWebSocket/ws Starts an echo server that listens on localhost:8008. It enforces client connections by requiring a specific value in the 'Authorization' HTTP header. ```bash $ ws echo_server --http_authorization_header supersecret [2020-12-17 22:35:06.192] [info] Listening on 127.0.0.1:8008 [2020-12-17 22:35:08.735] [info] New connection [2020-12-17 22:35:08.735] [info] remote ip: 127.0.0.1 [2020-12-17 22:35:08.735] [info] id: 0 [2020-12-17 22:35:08.735] [info] Uri: / [2020-12-17 22:35:08.735] [info] Headers: [2020-12-17 22:35:08.735] [info] Authorization: supersecret [2020-12-17 22:35:08.735] [info] Connection: Upgrade [2020-12-17 22:35:08.735] [info] Host: localhost:8008 [2020-12-17 22:35:08.735] [info] Sec-WebSocket-Extensions: permessage-deflate; server_max_window_bits=15; client_max_window_bits=15 [2020-12-17 22:35:08.735] [info] Sec-WebSocket-Key: eFF2Gf25dC7eC15Ab1135G== [2020-12-17 22:35:08.735] [info] Sec-WebSocket-Version: 13 [2020-12-17 22:35:08.735] [info] Upgrade: websocket [2020-12-17 22:35:08.735] [info] User-Agent: ixwebsocket/11.0.4 macos ssl/SecureTransport zlib 1.2.11 [2020-12-17 22:35:25.157] [info] Received 7 bytes ``` -------------------------------- ### Echo Server with Greeting Source: https://machinezone.github.io/IXWebSocket/CHANGELOG The `ws echo_server` can be started with a -g option to print a greeting message when a client connects. ```bash ws echo_server -g ``` -------------------------------- ### Exponential Backoff Log Source: https://machinezone.github.io/IXWebSocket/usage Example output showing wait times between reconnection attempts. ```text > Connection error: Got bad status connecting to foo.com, status: 301, HTTP Status line: HTTP/1.1 301 Moved Permanently #retries: 1 Wait time(ms): 100 #retries: 2 Wait time(ms): 200 #retries: 3 Wait time(ms): 400 #retries: 4 Wait time(ms): 800 #retries: 5 Wait time(ms): 1600 #retries: 6 Wait time(ms): 3200 #retries: 7 Wait time(ms): 6400 #retries: 8 Wait time(ms): 10000 ``` -------------------------------- ### Connect to WebSocket Endpoint Source: https://machinezone.github.io/IXWebSocket/ws Connects to a WebSocket endpoint and starts an interactive prompt for sending and receiving messages. Line editing is supported. Useful for testing service gracefulness with random data. ```bash ws connect wss://echo.websocket.org Type Ctrl-D to exit prompt... Connecting to url: wss://echo.websocket.org > ws_connect: connected Uri: / Handshake Headers: Connection: Upgrade Date: Tue, 08 Oct 2019 21:38:44 GMT Sec-WebSocket-Accept: 2j6LBScZveqrMx1W/GJkCWvZo3M= sec-websocket-extensions: Server: Kaazing Gateway Upgrade: websocket Received ping Received ping Received ping Hello world ! > Received 13 bytes ws_connect: received message: Hello world ! > Hello world ! > Received 13 bytes ws_connect: received message: Hello world ! ``` ```bash ws connect 'ws://jeanserge.com/v2?appkey=_pubsub' Type Ctrl-D to exit prompt... Connecting to url: ws://jeanserge.com/v2?appkey=_pubsub > ws_connect: connected Uri: /v2?appkey=_pubsub Handshake Headers: Connection: Upgrade Date: Tue, 08 Oct 2019 21:45:28 GMT Sec-WebSocket-Accept: LYHmjh9Gsu/Yw7aumQqyPObOEV4= Sec-WebSocket-Extensions: permessage-deflate; server_max_window_bits=15; client_max_window_bits=15 Server: Python/3.7 websockets/8.0.2 Upgrade: websocket bababababababab > ws_connect: connection closed: code 1000 reason ws_connect: connected Uri: /v2?appkey=_pubsub Handshake Headers: Connection: Upgrade Date: Tue, 08 Oct 2019 21:45:44 GMT Sec-WebSocket-Accept: I1rqxdLgTU+opPi5/zKPBTuXdLw= Sec-WebSocket-Extensions: permessage-deflate; server_max_window_bits=15; client_max_window_bits=15 Server: Python/3.7 websockets/8.0.2 Upgrade: websocket ``` -------------------------------- ### Configure Remote URL Source: https://machinezone.github.io/IXWebSocket/usage Sets the target URL for the WebSocket connection. Requires a stop and start cycle to apply changes to an active connection. ```cpp std::string url("wss://example.com"); websocket.configure(url); ``` -------------------------------- ### Sentry Rate Limiting Log Output Source: https://machinezone.github.io/IXWebSocket/CHANGELOG Example log output showing the system handling a 429 Too Many Requests error from Sentry by pausing transmission. ```text [2019-12-05 15:50:33.759] [info] messages received 2449 sent 3 [2019-12-05 15:50:34.759] [info] messages received 5533 sent 7 [2019-12-05 15:50:35.759] [info] messages received 8612 sent 11 [2019-12-05 15:50:36.759] [info] messages received 11562 sent 15 [2019-12-05 15:50:37.759] [info] messages received 14410 sent 19 [2019-12-05 15:50:38.759] [info] messages received 17236 sent 23 [2019-12-05 15:50:39.282] [error] Error sending data to sentry: 429 [2019-12-05 15:50:39.282] [error] Body: {"exception":[{"stacktrace":{"frames":[{"filename":"WorldScene.lua","function":"WorldScene.lua:1935","lineno":1958},{"filename":"WorldScene.lua","function":"onUpdate_WorldCam","lineno":1921},{"filename":"WorldMapTile.lua","function":"__index","lineno":239}]},"value":"noisytypes: Attempt to call nil(nil,2224139838)!"}],"platform":"python","sdk":{"name":"ws","version":"1.0.0"},"tags":[["game","niso"],["userid","107638363"],["environment","live"]],"timestamp":"2019-12-05T23:50:39Z"} [2019-12-05 15:50:39.282] [error] Response: {"error_name":"rate_limit","error":"Creation of this event was denied due to rate limiting"} [2019-12-05 15:50:39.282] [warning] Error 429 - Too Many Requests. ws will sleep and retry after 41 seconds [2019-12-05 15:50:39.760] [info] messages received 18839 sent 25 [2019-12-05 15:50:40.760] [info] messages received 18839 sent 25 [2019-12-05 15:50:41.760] [info] messages received 18839 sent 25 [2019-12-05 15:50:42.761] [info] messages received 18839 sent 25 [2019-12-05 15:50:43.762] [info] messages received 18839 sent 25 [2019-12-05 15:50:44.763] [info] messages received 18839 sent 25 [2019-12-05 15:50:45.768] [info] messages received 18839 sent 25 ``` -------------------------------- ### Implement WebSocket Server Source: https://machinezone.github.io/IXWebSocket/usage Initialize and run a WebSocket server with connection and message handling callbacks. ```cpp #include ... // Run a server on localhost at a given port. // Bound host name, max connections and listen backlog can also be passed in as parameters. int port = 8008; std::string host("127.0.0.1"); // If you need this server to be accessible on a different machine, use "0.0.0.0" ix::WebSocketServer server(port, host); server.setOnConnectionCallback( [&server](std::weak_ptr webSocket, std::shared_ptr connectionState) { std::cout << "Remote ip: " << connectionState->remoteIp << std::endl; auto ws = webSocket.lock(); if (ws) { ws->setOnMessageCallback( [webSocket, connectionState, &server](const ix::WebSocketMessagePtr msg) { if (msg->type == ix::WebSocketMessageType::Open) { std::cout << "New connection" << std::endl; // A connection state object is available, and has a default id // You can subclass ConnectionState and pass an alternate factory // to override it. It is useful if you want to store custom // attributes per connection (authenticated bool flag, attributes, etc...) std::cout << "id: " << connectionState->getId() << std::endl; // The uri the client did connect to. std::cout << "Uri: " << msg->openInfo.uri << std::endl; std::cout << "Headers:" << std::endl; for (auto it : msg->openInfo.headers) { std::cout << it.first << ": " << it.second << std::endl; } } else if (msg->type == ix::WebSocketMessageType::Message) { // For an echo server, we just send back to the client whatever was received by the server // All connected clients are available in an std::set. See the broadcast cpp example. // Second parameter tells whether we are sending the message in binary or text mode. // Here we send it in the same mode as it was received. auto ws = webSocket.lock(); if (ws) { ws->send(msg->str, msg->binary); } } } } ); } ); auto res = server.listen(); if (!res.first) { // Error handling return 1; } // Per message deflate connection is enabled by default. It can be disabled // which might be helpful when running on low power devices such as a Rasbery Pi server.disablePerMessageDeflate(); // Run the server in the background. Server can be stoped by calling server.stop() server.start(); // Block until server.stop() is called. server.wait(); ``` -------------------------------- ### View HTTP client help Source: https://machinezone.github.io/IXWebSocket/ws Displays the help menu for the ws curl HTTP client utility. ```bash $ ws curl --help HTTP Client Usage: ws curl [OPTIONS] url Positionals: url TEXT REQUIRED Connection url Options: -h,--help Print this help message and exit -d TEXT Form data -F TEXT Form data -H TEXT Header --output TEXT Output file -I Send a HEAD request -L Follow redirects --max-redirects INT Max Redirects -v Verbose -O Save output to disk --compress Enable gzip compression --connect-timeout INT Connection timeout --transfer-timeout INT Transfer timeout ``` -------------------------------- ### Network System Initialization Source: https://machinezone.github.io/IXWebSocket/usage On Windows, the network system must be initialized with WSAStartup() and cleaned up with WSACleanup(). Helper functions are provided for this purpose. ```APIDOC ## Network System Initialization ### Description Initializes the network system on Windows platforms. This is a prerequisite for using network functionalities. ### Method `ix::initNetSystem()` and `ix::uninitNetSystem()` ### Endpoint N/A (Library functions) ### Request Body N/A ### Response N/A ### Example ```cpp #include int main() { ix::initNetSystem(); // ... your network code ... ix::uninitNetSystem(); return 0; } ``` ``` -------------------------------- ### Build IXWebSocket with CMake Source: https://machinezone.github.io/IXWebSocket/build Standard commands to build the library from source using CMake. ```bash mkdir build #make a build dir so that you can build out of tree cd build cmake -DUSE_TLS=1 .. make -j ``` ```bash mkdir build cd build cmake -DUSE_TLS=1 .. make -j make install # will install to /usr/local on Unix, on macOS it is a good idea to sudo chown -R `whoami`:staff /usr/local ``` -------------------------------- ### Initialize Network System on Windows Source: https://machinezone.github.io/IXWebSocket/usage Initializes the network system on Windows using IXNetSystem. This should be called once in your main function before using network functionalities. Remember to call uninitNetSystem() when done. ```cpp #include int main() { ix::initNetSystem(); ... ix::uninitNetSystem(); return 0; } ``` -------------------------------- ### ReadyState Source: https://machinezone.github.io/IXWebSocket/usage Explains the different connection states that can be returned by the `getReadyState()` method. ```APIDOC ## ReadyState ### Description Describes the possible states of a WebSocket connection as returned by the `getReadyState()` method. ### Method `getReadyState()` ### Endpoint N/A (Client-side method) ### Parameters N/A ### Request Body N/A ### Response #### Success Response (200) An enum value representing the connection state: - `ReadyState::Connecting`: The connection is not yet open. - `ReadyState::Open`: The connection is open and ready to communicate. - `ReadyState::Closing`: The connection is in the process of closing. - `ReadyState::Closed`: The connection is closed or could not be opened. #### Response Example N/A ``` -------------------------------- ### Run echo client benchmark Source: https://machinezone.github.io/IXWebSocket/performance Connects to a server and displays message reception statistics without sending messages. ```bash $ ws echo_client -m ws://localhost:8008 [2020-08-02 12:31:17.284] [info] ws_echo_client: connected [2020-08-02 12:31:17.284] [info] Uri: / [2020-08-02 12:31:17.284] [info] Headers: [2020-08-02 12:31:17.284] [info] Connection: Upgrade [2020-08-02 12:31:17.284] [info] Sec-WebSocket-Accept: byy/pMK2d0PtRwExaaiOnXJTQHo= [2020-08-02 12:31:17.284] [info] Server: ixwebsocket/10.1.4 macos ssl/SecureTransport zlib 1.2.11 [2020-08-02 12:31:17.284] [info] Upgrade: websocket [2020-08-02 12:31:17.663] [info] messages received: 0 per second 2595307 total [2020-08-02 12:31:18.668] [info] messages received: 79679 per second 2674986 total [2020-08-02 12:31:19.668] [info] messages received: 207438 per second 2882424 total [2020-08-02 12:31:20.673] [info] messages received: 209207 per second 3091631 total [2020-08-02 12:31:21.676] [info] messages received: 216056 per second 3307687 total [2020-08-02 12:31:22.680] [info] messages received: 214927 per second 3522614 total [2020-08-02 12:31:23.684] [info] messages received: 216960 per second 3739574 total [2020-08-02 12:31:24.688] [info] messages received: 215232 per second 3954806 total [2020-08-02 12:31:25.691] [info] messages received: 212300 per second 4167106 total [2020-08-02 12:31:26.694] [info] messages received: 212501 per second 4379607 total [2020-08-02 12:31:27.699] [info] messages received: 212330 per second 4591937 total [2020-08-02 12:31:28.702] [info] messages received: 216511 per second 4808448 total ``` -------------------------------- ### Run IXWebSocket via Docker Source: https://machinezone.github.io/IXWebSocket/build Commands for running the ws tool and managing containers with docker-compose. ```bash docker run docker.pkg.github.com/machinezone/ixwebsocket/ws:latest --help ``` ```bash $ make docker ... $ docker compose up & ... $ docker exec -it ixwebsocket_ws_1 bash app@ca2340eb9106:~$ ws --help ``` -------------------------------- ### Display ws help message Source: https://machinezone.github.io/IXWebSocket/ws View the available subcommands and options for the ws tool. ```bash ws is a websocket tool Usage: ws [OPTIONS] SUBCOMMAND Options: -h,--help Print this help message and exit Subcommands: send Send a file receive Receive a file transfer Broadcasting server connect Connect to a remote server chat Group chat echo_server Echo server broadcast_server Broadcasting server ping Ping pong curl HTTP Client httpd HTTP server ``` -------------------------------- ### Run Simple HTTP Server Source: https://machinezone.github.io/IXWebSocket/CHANGELOG The `httpd` command can be used to run a simple web server that serves local files. This feature is still in early development. ```bash httpd ``` -------------------------------- ### Download IXWebSocket Release Source: https://machinezone.github.io/IXWebSocket/packages Download the latest release tarball from GitHub. Ensure the version matches the desired update. ```bash $ cd /tmp /tmp$ curl -s -O -L https://github.com/machinezone/IXWebSocket/archive/v9.1.9.tar.gz ``` -------------------------------- ### Build for macOS and iOS Source: https://machinezone.github.io/IXWebSocket/build Build script usage for Apple platforms. ```bash mkdir build cd build ./../tools/build_ios.sh ``` -------------------------------- ### Configure TLS Options for WebSocket Source: https://machinezone.github.io/IXWebSocket/usage Use this to set TLS certificate and key files, as well as the CA bundle for verifying peer certificates. Ensure `tls` is set to `true` in server mode. ```cpp webSocket.setTLSOptions({ .certFile = "path/to/cert/file.pem", .keyFile = "path/to/key/file.pem", .caFile = "path/to/trust/bundle/file.pem", // as a file, or in memory buffer in PEM format .tls = true // required in server mode }); ``` -------------------------------- ### Keyboard shortcuts Source: https://machinezone.github.io/IXWebSocket/performance List of keyboard shortcuts for navigation. ```text ? n p s ``` -------------------------------- ### Prepare for Pull Request Source: https://machinezone.github.io/IXWebSocket/packages Fetch upstream changes, reset the local master branch, and create a new branch for the update. Commit the changes with a descriptive message. ```bash git fetch upstream git co master git reset --hard upstream/master git push origin master --force vcpkg$ git co -b feature/ixwebsocket_9.1.9 M ports/ixwebsocket/CONTROL M ports/ixwebsocket/portfile.cmake Switched to a new branch 'feature/ixwebsocket_9.1.9' vcpkg$ vcpkg$ vcpkg$ git commit -am 'ixwebsocket: update to 9.1.9' [feature/ixwebsocket_9.1.9 8587a4881] ixwebsocket: update to 9.1.9 2 files changed, 3 insertions(+), 3 deletions(-) vcpkg$ ``` -------------------------------- ### Handle HTTP Requests with Callbacks Source: https://machinezone.github.io/IXWebSocket/usage Implementation of the setOnConnectionCallback to process incoming requests and return custom responses. ```cpp setOnConnectionCallback( [this](HttpRequestPtr request, std::shared_ptr connectionState) -> HttpResponsePtr { // Build a string for the response std::stringstream ss; ss << connectionState->getRemoteIp(); << " " << request->method << " " << request->uri; std::string content = ss.str(); return std::make_shared(200, "OK", HttpErrorCode::Ok, WebSocketHttpHeaders(), content); } ``` -------------------------------- ### Build for Android Source: https://machinezone.github.io/IXWebSocket/build Build script usage for Android targets. ```bash mkdir build cd build ./../tools/build_android.sh make -j ``` -------------------------------- ### Manage Subprotocols Source: https://machinezone.github.io/IXWebSocket/usage Configures supported subprotocols for the handshake and retrieves the negotiated protocol from the open info. ```cpp webSocket.addSubprotocol("appProtocol-v1"); webSocket.addSubprotocol("appProtocol-v2"); ``` ```cpp std::cout << "protocol: " << msg->openInfo.protocol << std::endl; ``` -------------------------------- ### Configure proxy mapping Source: https://machinezone.github.io/IXWebSocket/ws Defines hostname-to-server mappings in a configuration file for routing traffic to different backends. ```text echo.jeanserge.com=ws://localhost:8008 bavarde.jeanserge.com=ws://localhost:5678 ``` -------------------------------- ### Perform Asynchronous HTTP Requests Source: https://machinezone.github.io/IXWebSocket/usage Shows how to use the asynchronous mode of HttpClient with chunk callbacks and background thread processing. ```cpp // // Asynchronous Request // bool async = true; HttpClient httpClient(async); auto args = httpClient.createRequest(url, HttpClient::kGet); // If you define a chunk callback it will be called repeteadly with the // incoming data. This allows to process data on the go or write it to disk // instead of accumulating the data in memory. args.onChunkCallback = [](const std::string& data) { // process data }; // Push the request to a queue, bool ok = httpClient.performRequest(args, [](const HttpResponsePtr& response) { // This callback execute in a background thread. Make sure you uses appropriate protection such as mutex auto statusCode = response->statusCode; // acess results // response->body is empty if onChunkCallback was used } ); // ok will be false if your httpClient is not async // A request in progress can be cancelled by setting the cancel flag. It does nothing if the request already completed. args->cancel = true; ``` -------------------------------- ### WebSocket Server API Source: https://machinezone.github.io/IXWebSocket/usage Implementation details for running a WebSocket server, including connection callbacks and message handling. ```APIDOC ## WebSocketServer ### Description Initializes and runs a WebSocket server. Uses a weak_ptr for connection callbacks to prevent memory leaks. ### Methods - `ix::WebSocketServer(int port, std::string host)`: Constructor to initialize server. - `setOnConnectionCallback(callback)`: Sets the callback for new connections. - `listen()`: Starts listening on the specified port/host. - `start()`: Starts the server in the background. - `stop()`: Stops the server. - `wait()`: Blocks until the server stops. - `disablePerMessageDeflate()`: Disables per-message deflate compression. ``` -------------------------------- ### WebSocket Client API Source: https://machinezone.github.io/IXWebSocket/usage Demonstrates the usage of the WebSocket client API, including setting the URL, configuring heartbeats, enabling/disabling per-message deflate, setting message callbacks, sending messages, and stopping the connection. ```APIDOC ## WebSocket Client API ### Description This section details how to use the WebSocket client to establish a connection, send and receive messages, and manage the connection lifecycle. ### Method `ix::WebSocket` class methods ### Endpoint `ws://:/` (Example URL) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```cpp #include #include // Our websocket object ix::WebSocket webSocket; std::string url("ws://localhost:8080/"); webSocket.setUrl(url); // Optional heart beat, sent every 45 seconds when there is not any traffic webSocket.setPingInterval(45); // Per message deflate connection is not enabled by default. webSocket.enablePerMessageDeflate(); // webSocket.disablePerMessageDeflate(); // Setup a callback to be fired when a message or an event (open, close, error) is received webSocket.setOnMessageCallback([](const ix::WebSocketMessagePtr& msg) { if (msg->type == ix::WebSocketMessageType::Message) { std::cout << msg->str << std::endl; } } ); // Start the background thread to receive messages webSocket.start(); // Send a message to the server (default to TEXT mode) webSocket.send("hello world"); // The message can be sent in BINARY mode webSocket.sendBinary("some serialized binary data"); // ... finally ... // Stop the connection webSocket.stop(); ``` ### Response #### Success Response (200) N/A (Callbacks handle messages and events) #### Response Example N/A ``` -------------------------------- ### Handle Incorrect Headers Source: https://machinezone.github.io/IXWebSocket/ws Demonstrates the connection closing with a custom code (4001) and reason ('Permission denied') when an incorrect authorization header is provided. ```bash [2020-12-17 22:39:37.044] [info] Upgrade: websocket ws_connect: connection closed: code 4001 reason Permission denied ``` -------------------------------- ### Send UTF-8 Text and Binary Data Source: https://machinezone.github.io/IXWebSocket/usage Demonstrates sending binary data using std::vector and sending UTF-8 encoded text using a C-style string with a specified length. These methods can be more efficient than std::string for known data types. ```cpp std::vector data({1, 2, 3, 4}); auto result = webSocket.sendBinary(data); const char* text = "Hello World!"; result = webSocket.sendUtf8Text(IXWebSocketSendData(text, strlen(text))); ``` -------------------------------- ### Integrate vcpkg with CMake Source: https://machinezone.github.io/IXWebSocket/build Configuration required to link the vcpkg-installed library in a CMake project. ```cmake set(CMAKE_TOOLCHAIN_FILE "$ENV{VCPKG_ROOT}/scripts/buildsystems/vcpkg.cmake" CACHE STRING "") # this is super important in order for cmake to include the vcpkg search/lib paths! # find library and its headers find_path(IXWEBSOCKET_INCLUDE_DIR ixwebsocket/IXWebSocket.h) find_library(IXWEBSOCKET_LIBRARY ixwebsocket) # include headers include_directories(${IXWEBSOCKET_INCLUDE_DIR}) # ... target_link_libraries(${PROJECT_NAME} ... ${IXWEBSOCKET_LIBRARY}) # Cmake will automatically fail the generation if the lib was not found, i.e is set to NOTFOUND ``` -------------------------------- ### WebSocket Send with Progress Callback Source: https://machinezone.github.io/IXWebSocket/usage Sends binary data with an optional progress callback to monitor sending progress and potentially cancel slow sends. The callback is invoked for each fragment sent. ```cpp auto result = _webSocket.sendBinary(serializedMsg, [this, throttle](int current, int total) -> bool { spdlog::info("ws_send: Step {} out of {}", current + 1, total); if (throttle) { std::chrono::duration duration(10); std::this_thread::sleep_for(duration); } return _connected; }); ``` -------------------------------- ### Configure HTTP Server Redirect Source: https://machinezone.github.io/IXWebSocket/CHANGELOG Command line usage for the ws httpd server to redirect incoming requests to a specified URL. ```bash ws httpd -L --redirect_url https://www.google.com ``` -------------------------------- ### Handle Open and Close Notifications Source: https://machinezone.github.io/IXWebSocket/usage Registers a callback to handle connection open and close events, including inspecting handshake headers and close information. ```cpp webSocket.setOnMessageCallback([](const ix::WebSocketMessagePtr& msg) { if (msg->type == ix::WebSocketMessageType::Open) { std::cout << "send greetings" << std::endl; // Headers can be inspected (pairs of string/string) std::cout << "Handshake Headers:" << std::endl; for (auto it : msg->headers) { std::cout << it.first << ": " << it.second << std::endl; } } else if (msg->type == ix::WebSocketMessageType::Close) { std::cout << "disconnected" << std::endl; // The server can send an explicit code and reason for closing. // This data can be accessed through the closeInfo object. std::cout << msg->closeInfo.code << std::endl; std::cout << msg->closeInfo.reason << std::endl; } } ); ``` -------------------------------- ### HTTP Client (ws curl) Source: https://machinezone.github.io/IXWebSocket/ws A command-line HTTP client similar to curl for making requests via the IXWebSocket toolset. ```APIDOC ## HTTP Client (ws curl) ### Description Performs HTTP requests using the `ws curl` command. ### Usage `ws curl [OPTIONS] url` ### Parameters - **url** (string) - Required - The target connection URL. - **-d** (string) - Optional - Form data. - **-H** (string) - Optional - Header. - **-I** (flag) - Optional - Send a HEAD request. - **-L** (flag) - Optional - Follow redirects. - **--output** (string) - Optional - Output file path. - **--connect-timeout** (int) - Optional - Connection timeout in seconds. ``` -------------------------------- ### Verify Downloaded Archive Source: https://machinezone.github.io/IXWebSocket/packages Calculate the SHA512 checksum of the downloaded tarball to ensure its integrity. This value is used in the vcpkg portfile. ```bash /tmp$ openssl sha512 v9.1.9.tar.gz SHA512(v9.1.9.tar.gz)= f1fd731b5f6a9ce6d6d10bee22a5d9d9baaa8ea0564d6c4cd7eb91dcb88a45c49b2c7fdb75f8640a3589c1b30cee33ef5df8dcbb55920d013394d1e33ddd3c8e ``` -------------------------------- ### WebSocket Send in Binary Mode Source: https://machinezone.github.io/IXWebSocket/CHANGELOG The `ws connect` command now supports sending messages in binary mode using a new option. By default, it sends in text mode. ```bash ws connect --binary ws://example.com ``` -------------------------------- ### HTTP Server API Source: https://machinezone.github.io/IXWebSocket/usage The HttpServer class allows for hosting an HTTP server, with the ability to define custom connection callbacks to process incoming requests. ```APIDOC ## HTTP Server API ### Description Initialize and start an HTTP server, and define custom logic for processing incoming requests via setOnConnectionCallback. ### Method - listen() - start() ### Parameters #### Connection Callback - **request** (HttpRequestPtr) - The incoming HTTP request object. - **connectionState** (ConnectionState) - The state of the current connection. ### Response - Returns an HttpResponsePtr containing the status code, status message, error code, headers, and body content. ``` -------------------------------- ### Supply Extra HTTP Headers Source: https://machinezone.github.io/IXWebSocket/usage Adds custom HTTP headers to be included in the initial WebSocket handshake. ```cpp WebSocketHttpHeaders headers; headers["foo"] = "bar"; webSocket.setExtraHeaders(headers); ```