1 Utility Client Example Application Tutorial
2 ===========================================
4 Chapter 1: Initial Setup & Basics
5 ---------------------------------
7 Setting up the basic types, opening and closing connections, sending and receiving messages.
11 A basic program loop that prompts the user for a command and then processes it. In this tutorial we will modify this program to perform tasks and retrieve data from a remote server over a WebSocket connection.
18 *note* A code snapshot for each step is present next to this tutorial file in the git repository.
29 std::cout << "Enter Command: ";
30 std::getline(std::cin, input);
32 if (input == "quit") {
34 } else if (input == "help") {
36 << "\nCommand List:\n"
37 << "help: Display this help text\n"
38 << "quit: Exit the program\n"
41 std::cout << "Unrecognized Command" << std::endl;
51 _Add WebSocket++ includes and set up an endpoint type._
53 WebSocket++ includes two major object types. The endpoint and the connection. The
54 endpoint creates and launches new connections and maintains default settings for
55 those connections. Endpoints also manage any shared network resources.
57 The connection stores information specific to each WebSocket session.
59 > **Note:** Once a connection is launched, there is no link between the endpoint and the connection. All default settings are copied into the new connection by the endpoint. Changing default settings on an endpoint will only affect future connections.
60 Connections do not maintain a link back to their associated endpoint. Endpoints do not maintain a list of outstanding connections. If your application needs to iterate over all connections it will need to maintain a list of them itself.
62 WebSocket++ endpoints are built by combining an endpoint role with an endpoint config. There are two different types of endpoint roles, one each for the client and server roles in a WebSocket session. This is a client tutorial so we will use the client role `websocketpp::client` which is provided by the `<websocketpp/client.hpp>` header.
64 > ##### Terminology: Endpoint Config
65 > WebSocket++ endpoints have a group of settings that may be configured at compile time via the `config` template parameter. A config is a struct that contains types and static constants that are used to produce an endpoint with specific properties. Depending on which config is being used the endpoint will have different methods available and may have additional third party dependencies.
67 The endpoint role takes a template parameter called `config` that is used to configure the behavior of endpoint at compile time. For this example we are going to use a default config provided by the library called `asio_client`, provided by `<websocketpp/config/asio_no_tls_client.hpp>`. This is a client config that uses boost::asio to provide network transport and does not support TLS based security. Later on we will discuss how to introduce TLS based security into a WebSocket++ application, more about the other stock configs, and how to build your own custom configs.
69 Combine a config with an endpoint role to produce a fully configured endpoint. This type will be used frequently so I would recommend a typedef here.
71 `typedef websocketpp::client<websocketpp::config::asio_client> client`
74 Adding WebSocket++ has added a few dependencies to our program that must be addressed in the build system. Firstly, the WebSocket++ and Boost library headers must be in the include search path of your build system. How exactly this is done depends on where you have the WebSocket++ headers installed and what build system you are using.
76 In addition to the new headers, boost::asio depends on the `boost_system` shared library. This will need to be added (either as a static or dynamic) to the linker. Refer to your build environment documentation for instructions on linking to shared libraries.
78 `clang++ step2.cpp -lboost_system`
82 #include <websocketpp/config/asio_no_tls_client.hpp>
83 #include <websocketpp/client.hpp>
88 typedef websocketpp::client<websocketpp::config::asio_client> client;
95 std::cout << "Enter Command: ";
96 std::getline(std::cin, input);
98 if (input == "quit") {
100 } else if (input == "help") {
102 << "\nCommand List:\n"
103 << "help: Display this help text\n"
104 << "quit: Exit the program\n"
107 std::cout << "Unrecognized Command" << std::endl;
117 _Create endpoint wrapper object that handles initialization and setting up the background thread._
119 In order to process user input while network processing occurs in the background we are going to use a separate thread for the WebSocket++ processing loop. This leaves the main thread free to process foreground user input. In order to enable simple RAII style resource management for our thread and endpoint we will use a wrapper object that configures them both in its constructor.
121 > ##### Terminology: websocketpp::lib namespace
122 > WebSocket++ is designed to be used with a C++11 standard library. As this is not universally available in popular build systems the Boost libraries may be used as polyfills for the C++11 standard library in C++98 build environments. The `websocketpp::lib` namespace is used by the library and its associated examples to abstract away the distinctions between the two. `websocketpp::lib::shared_ptr` will evaluate to `std::shared_ptr` in a C++11 environment and `boost::shared_ptr` otherwise.
124 > This tutorial uses the `websocketpp::lib` wrappers because it doesn't know what the build environment of the reader is. For your applications, unless you are interested in similar portability, are free to use the boost or std versions of these types directly.
126 >[TODO: link to more information about websocketpp::lib namespace and C++11 setup]
128 Within the `websocket_endpoint` constructor several things happen:
130 First, we set the endpoint logging behavior to silent by clearing all of the access and error logging channels. [TODO: link to more information about logging]
132 m_endpoint.clear_access_channels(websocketpp::log::alevel::all);
133 m_endpoint.clear_error_channels(websocketpp::log::elevel::all);
136 Next, we initialize the transport system underlying the endpoint and set it to perpetual mode. In perpetual mode the endpoint's processing loop will not exit automatically when it has no connections. This is important because we want this endpoint to remain active while our application is running and process requests for new WebSocket connections on demand as we need them. Both of these methods are specific to the asio transport. They will not be necessary or present in endpoints that use a non-asio config.
138 m_endpoint.init_asio();
139 m_endpoint.start_perpetual();
142 Finally, we launch a thread to run the `run` method of our client endpoint. While the endpoint is running it will process connection tasks (read and deliver incoming messages, frame and send outgoing messages, etc). Because it is running in perpetual mode, when there are no connections active it will wait for a new connection.
144 m_thread.reset(new websocketpp::lib::thread(&client::run, &m_endpoint));
149 Now that our client endpoint template is actually instantiated a few more linker dependencies will show up. In particular, WebSocket clients require a cryptographically secure random number generator. WebSocket++ is able to use either `boost_random` or the C++11 standard library <random> for this purpose. Because this example also uses threads, if we do not have C++11 std::thread available we will need to include `boost_thread`.
151 ##### Clang (C++98 & boost)
152 `clang++ step3.cpp -lboost_system -lboost_random -lboost_thread`
155 `clang++ -std=c++0x -stdlib=libc++ step3.cpp -lboost_system -D_WEBSOCKETPP_CPP11_STL_`
157 ##### G++ (C++98 & Boost)
158 `g++ step3.cpp -lboost_system -lboost_random -lboost_thread`
160 ##### G++ v4.6+ (C++11)
161 `g++ -std=c++0x step3.cpp -lboost_system -D_WEBSOCKETPP_CPP11_STL_`
166 #include <websocketpp/config/asio_no_tls_client.hpp>
167 #include <websocketpp/client.hpp>
169 #include <websocketpp/common/thread.hpp>
170 #include <websocketpp/common/memory.hpp>
175 typedef websocketpp::client<websocketpp::config::asio_client> client;
177 class websocket_endpoint {
179 websocket_endpoint () {
180 m_endpoint.clear_access_channels(websocketpp::log::alevel::all);
181 m_endpoint.clear_error_channels(websocketpp::log::elevel::all);
183 m_endpoint.init_asio();
184 m_endpoint.start_perpetual();
186 m_thread.reset(new websocketpp::lib::thread(&client::run, &m_endpoint));
190 websocketpp::lib::shared_ptr<websocketpp::lib::thread> m_thread;
196 websocket_endpoint endpoint;
199 std::cout << "Enter Command: ";
200 std::getline(std::cin, input);
202 if (input == "quit") {
204 } else if (input == "help") {
206 << "\nCommand List:\n"
207 << "help: Display this help text\n"
208 << "quit: Exit the program\n"
211 std::cout << "Unrecognized Command" << std::endl;
221 _Opening WebSocket connections_
223 This step adds two new commands to utility_client. The ability to open a new connection and the ability to view information about a previously opened connection. Every connection that gets opened will be assigned an integer connection id that the user of the program can use to interact with that connection.
225 #### New Connection Metadata Object
227 In order to track information about each connection a `connection_metadata` object is defined. This object stores the numeric connection id and a number of fields that will be filled in as the connection is processed. Initially this includes the state of the connection (opening, open, failed, closed, etc), the original URI connected to, an identifying value from the server, and a description of the reason for connection failure/closure. Future steps will add more information to this metadata object.
229 #### Update `websocket_endpoint`
231 The `websocket_endpoint` object has gained some new data members and methods. It now tracks a mapping between connection IDs and their associated metadata as well as the next sequential ID number to hand out. The `connect()` method initiates a new connection. The `get_metadata` method retrieves metadata given an ID.
233 #### The connect method
234 A new WebSocket connection is initiated via a three step process. First, a connection request is created by `endpoint::get_connection(uri)`. Next, the connection request is configured. Lastly, the connection request is submitted back to the endpoint via `endpoint::connect()` which adds it to the queue of new connections to make.
236 > ##### Terminology `connection_ptr`
237 > WebSocket++ keeps track of connection related resources using a reference counted shared pointer. The type of this pointer is `endpoint::connection_ptr`. A `connection_ptr` allows direct access to information about the connection and allows changing connection settings. Because of this direct access and their internal resource management role within the library it is not safe for end applications to use `connection_ptr` except in the specific circumstances detailed below.
239 > **When is it safe to use `connection_ptr`?**
240 > - After `endpoint::get_connection(...)` and before `endpoint::connect()`: `get_connection` returns a `connection_ptr`. It is safe to use this pointer to configure your new connection. Once you submit the connection to `connect` you may no longer use the `connection_ptr` and should discard it immediately for optimal memory management.
241 > - During a handler: WebSocket++ allows you to register hooks / callbacks / event handlers for specific events that happen during a connection's lifetime. During the invocation of one of these handlers the library guarantees that it is safe to use a `connection_ptr` for the connection associated with the currently running handler.
243 > ##### Terminology `connection_hdl`
244 > Because of the limited thread safety of the `connection_ptr` the library also provides a more flexible connection identifier, the `connection_hdl`. The `connection_hdl` has type `websocketpp::connection_hdl` and it is defined in `<websocketpp/common/connection_hdl.hpp>`. Note that unlike `connection_ptr` this is not dependent on the type or config of the endpoint. Code that simply stores or transmits `connection_hdl` but does not use them can include only the header above and can treat its hdls like values.
246 > Connection handles are not used directly. They are used by endpoint methods to identify the target of the desired action. For example, the endpoint method that sends a new message will take as a parameter the hdl of the connection to send the message to.
248 > **When is it safe to use `connection_hdl`?**
249 > `connection_hdl`s may be used at any time from any thread. They may be copied and stored in containers. Deleting a hdl will not affect the connection in any way. Handles may be upgraded to a `connection_ptr` during a handler call by using `endpoint::get_con_from_hdl()`. The resulting `connection_ptr` is safe to use for the duration of that handler invocation.
251 > **`connection_hdl` FAQs**
252 > - `connection_hdl`s are guaranteed to be unique within a program. Multiple endpoints in a single program will always create connections with unique handles.
253 > - Using a `connection_hdl` with a different endpoint than the one that created its associated connection will result in undefined behavior.
254 > - Using a `connection_hdl` whose associated connection has been closed or deleted is safe. The endpoint will return a specific error saying the operation couldn't be completed because the associated connection doesn't exist.
255 > [TODO: more here? link to a connection_hdl FAQ elsewhere?]
257 `websocket_endpoint::connect()` begins by calling `endpoint::get_connection()` using a uri passed as a parameter. Additionally, an error output value is passed to capture any errors that might occur during. If an error does occur an error notice is printed along with a descriptive message and the -1 / 'invalid' value is returned as the new ID.
259 > ###### Terminology: `error handling: exceptions vs error_code`
260 > WebSocket++ uses the error code system defined by the C++11 `<system_error>` library. It can optionally fall back to a similar system provided by the Boost libraries. All user facing endpoint methods that can fail take an `error_code` in an output parameter and store the error that occured there before returning. An empty/default constructed value is returned in the case of success.
262 > **Exception throwing varients**
263 > All user facing endpoint methods that take and use an `error_code` parameter have a version that throws an exception instead. These methods are identical in function and signature except for the lack of the final ec parameter. The type of the exception thrown is `websocketpp::exception`. This type derives from `std::exception` so it can be caught by catch blocks grabbing generic `std::exception`s. The `websocketpp::exception::code()` method may be used to extract the machine readable `error_code` value from an exception.
265 > For clarity about error handling the utility_client example uses exclusively the exception free varients of these methods. Your application may choose to use either.
267 If connection creation succeeds, the next sequential connection ID is generated and a `connection_metadata` object is inserted into the connection list under that ID. Initially the metadata object stores the connection ID, the `connection_hdl`, and the URI the connection was opened to.
270 int new_id = m_next_id++;
271 metadata_ptr metadata(new connection_metadata(new_id, con->get_handle(), uri));
272 m_connection_list[new_id] = metadata;
275 Next, the connection request is configured. For this step the only configuration we will do is setting up a few default handlers. Later on we will return and demonstrate some more detailed configuration that can happen here (setting user agents, origin, proxies, custom headers, subprotocols, etc).
277 > ##### Terminology: Registering handlers
278 > WebSocket++ provides a number of execution points where you can register to have a handler run. Which of these points are available to your endpoint will depend on its config. TLS handlers will not exist on non-TLS endpoints for example. A complete list of handlers can be found at http://www.zaphoyd.com/websocketpp/manual/reference/handler-list.
280 > Handlers can be registered at the endpoint level and at the connection level. Endpoint handlers are copied into new connections as they are created. Changing an endpoint handler will affect only future connections. Handlers registered at the connection level will be bound to that specific connection only.
282 > The signature of handler binding methods is the same for endpoints and connections. The format is: `set_*_handler(...)`. Where * is the name of the handler. For example, `set_open_handler(...)` will set the handler to be called when a new connection is open. `set_fail_handler(...)` will set the handler to be called when a connection fails to connect.
284 > All handlers take one argument, a callable type that can be converted to a `std::function` with the correct count and type of arguments. You can pass free functions, functors, and Lambdas with matching argument lists as handlers. In addition, you can use `std::bind` (or `boost::bind`) to register functions with non-matching argument lists. This is useful for passing additional parameters not present in the handler signature or member functions that need to carry a 'this' pointer.
286 > The function signature of each handler can be looked up in the list above in the manual. In general, all handlers include the `connection_hdl` identifying which connection this even is associated with as the first parameter. Some handlers (such as the message handler) include additional parameters. Most handlers have a void return value but some (`validate`, `ping`, `tls_init`) do not. The specific meanings of the return values are documented in the handler list linked above.
288 `utility_client` registers an open and a fail handler. We will use these to track whether each connection was successfully opened or failed. If it successfully opens, we will gather some information from the opening handshake and store it with our connection metadata.
290 In this example we are going to set connection specific handlers that are bound directly to the metadata object associated with our connection. This allows us to avoid performing a lookup in each handler to find the metadata object we plan to update which is a bit more efficient.
292 Lets look at the parameters being sent to bind in detail:
295 con->set_open_handler(websocketpp::lib::bind(
296 &connection_metadata::on_open,
299 websocketpp::lib::placeholders::_1
303 `&connection_metadata::on_open` is the address of the `on_open` member function of the `connection_metadata` class. `metadata_ptr` is a pointer to the `connection_metadata` object associated with this class. It will be used as the object on which the `on_open` member function will be called. `&m_endpoint` is the address of the endpoint in use. This parameter will be passed as-is to the `on_open` method. Lastly, `websocketpp::lib::placeholders::_1` is a placeholder indicating that the bound function should take one additional argument to be filled in at a later time. WebSocket++ will fill in this placeholder with the `connection_hdl` when it invokes the handler.
305 Finally, we call `endpoint::connect()` on our configured connection request and return the new connection ID.
307 #### Handler Member Functions
309 The open handler we registered, `connection_metadata::on_open`, sets the status metadata field to "Open" and retrieves the value of the "Server" header from the remote endpoint's HTTP response and stores it in the metadata object. Servers often set an identifying string in this header.
311 The fail handler we registered, `connection_metadata::on_fail`, sets the status metadata field to "Failed", the server field similarly to `on_open`, and retrieves the error code describing why the connection failed. The human readable message associated with that error code is saved to the metadata object.
315 Two new commands have been set up. "connect [uri]" will pass the URI to the `websocket_endpoint` connect method and report an error or the connection ID of the new connection. "show [connection id]" will retrieve and print out the metadata associated with that connection. The help text has been updated accordingly.
318 } else if (input.substr(0,7) == "connect") {
319 int id = endpoint.connect(input.substr(8));
321 std::cout << "> Created connection with id " << id << std::endl;
323 } else if (input.substr(0,4) == "show") {
324 int id = atoi(input.substr(5).c_str());
326 connection_metadata::ptr metadata = endpoint.get_metadata(id);
328 std::cout << *metadata << std::endl;
330 std::cout << "> Unknown connection id " << id << std::endl;
337 There are no changes to the build instructions from step 3
342 Enter Command: connect not a websocket uri
343 > Connect initialization error: invalid uri
344 Enter Command: show 0
345 > Unknown connection id 0
346 Enter Command: connect ws://echo.websocket.org
347 > Created connection with id 0
348 Enter Command: show 0
349 > URI: ws://echo.websocket.org
351 > Remote Server: Kaazing Gateway
352 > Error/close reason: N/A
353 Enter Command: connect ws://wikipedia.org
354 > Created connection with id 1
355 Enter Command: show 1
356 > URI: ws://wikipedia.org
358 > Remote Server: Apache
359 > Error/close reason: Invalid HTTP status.
365 #include <websocketpp/config/asio_no_tls_client.hpp>
366 #include <websocketpp/client.hpp>
368 #include <websocketpp/common/thread.hpp>
369 #include <websocketpp/common/memory.hpp>
377 typedef websocketpp::client<websocketpp::config::asio_client> client;
379 class connection_metadata {
381 typedef websocketpp::lib::shared_ptr<connection_metadata> ptr;
383 connection_metadata(int id, websocketpp::connection_hdl hdl, std::string uri)
386 , m_status("Connecting")
391 void on_open(client * c, websocketpp::connection_hdl hdl) {
394 client::connection_ptr con = c->get_con_from_hdl(hdl);
395 m_server = con->get_response_header("Server");
398 void on_fail(client * c, websocketpp::connection_hdl hdl) {
401 client::connection_ptr con = c->get_con_from_hdl(hdl);
402 m_server = con->get_response_header("Server");
403 m_error_reason = con->get_ec().message();
406 friend std::ostream & operator<< (std::ostream & out, connection_metadata const & data);
409 websocketpp::connection_hdl m_hdl;
410 std::string m_status;
412 std::string m_server;
413 std::string m_error_reason;
416 std::ostream & operator<< (std::ostream & out, connection_metadata const & data) {
417 out << "> URI: " << data.m_uri << "\n"
418 << "> Status: " << data.m_status << "\n"
419 << "> Remote Server: " << (data.m_server.empty() ? "None Specified" : data.m_server) << "\n"
420 << "> Error/close reason: " << (data.m_error_reason.empty() ? "N/A" : data.m_error_reason);
425 class websocket_endpoint {
427 websocket_endpoint () : m_next_id(0) {
428 m_endpoint.clear_access_channels(websocketpp::log::alevel::all);
429 m_endpoint.clear_error_channels(websocketpp::log::elevel::all);
431 m_endpoint.init_asio();
432 m_endpoint.start_perpetual();
434 m_thread.reset(new websocketpp::lib::thread(&client::run, &m_endpoint));
437 int connect(std::string const & uri) {
438 websocketpp::lib::error_code ec;
440 client::connection_ptr con = m_endpoint.get_connection(uri, ec);
443 std::cout << "> Connect initialization error: " << ec.message() << std::endl;
447 int new_id = m_next_id++;
448 connection_metadata::ptr metadata_ptr(new connection_metadata(new_id, con->get_handle(), uri));
449 m_connection_list[new_id] = metadata_ptr;
451 con->set_open_handler(websocketpp::lib::bind(
452 &connection_metadata::on_open,
455 websocketpp::lib::placeholders::_1
457 con->set_fail_handler(websocketpp::lib::bind(
458 &connection_metadata::on_fail,
461 websocketpp::lib::placeholders::_1
464 m_endpoint.connect(con);
469 connection_metadata::ptr get_metadata(int id) const {
470 con_list::const_iterator metadata_it = m_connection_list.find(id);
471 if (metadata_it == m_connection_list.end()) {
472 return connection_metadata::ptr();
474 return metadata_it->second;
478 typedef std::map<int,connection_metadata::ptr> con_list;
481 websocketpp::lib::shared_ptr<websocketpp::lib::thread> m_thread;
483 con_list m_connection_list;
490 websocket_endpoint endpoint;
493 std::cout << "Enter Command: ";
494 std::getline(std::cin, input);
496 if (input == "quit") {
498 } else if (input == "help") {
500 << "\nCommand List:\n"
501 << "connect <ws uri>\n"
502 << "show <connection id>\n"
503 << "help: Display this help text\n"
504 << "quit: Exit the program\n"
506 } else if (input.substr(0,7) == "connect") {
507 int id = endpoint.connect(input.substr(8));
509 std::cout << "> Created connection with id " << id << std::endl;
511 } else if (input.substr(0,4) == "show") {
512 int id = atoi(input.substr(5).c_str());
514 connection_metadata::ptr metadata = endpoint.get_metadata(id);
516 std::cout << *metadata << std::endl;
518 std::cout << "> Unknown connection id " << id << std::endl;
521 std::cout << "> Unrecognized Command" << std::endl;
531 _Closing connections_
533 This step adds a command that allows you to close a WebSocket connection and adjusts the quit command so that it cleanly closes all outstanding connections before quitting.
535 #### Getting connection close information out of WebSocket++
537 > ##### Terminology: WebSocket close codes & reasons
538 > The WebSocket close handshake involves an exchange of optional machine readable close codes and human readable reason strings. Each endpoint sends independent close details. The codes are short integers. The reasons are UTF8 text strings of at most 125 characters. More details about valid close code ranges and the meaning of each code can be found at https://tools.ietf.org/html/rfc6455#section-7.4
540 The `websocketpp::close::status` namespace contains named constants for all of the IANA defined close codes. It also includes free functions to determine whether a value is reserved or invalid and to convert a code to a human readable text representation.
542 During the close handler call WebSocket++ connections offer the following methods for accessing close handshake information:
544 - `connection::get_remote_close_code()`: Get the close code as reported by the remote endpoint
545 - `connection::get_remote_close_reason()`: Get the close reason as reported by the remote endpoint
546 - `connection::get_local_close_code()`: Get the close code that this endpoint sent.
547 - `connection::get_local_close_reason()`: Get the close reason that this endpoint sent.
548 - `connection::get_ec()`: Get a more detailed/specific WebSocket++ `error_code` indicating what library error (if any) ultimately resulted in the connection closure.
550 *Note:* there are some special close codes that will report a code that was not actually sent on the wire. For example 1005/"no close code" indicates that the endpoint omitted a close code entirely and 1006/"abnormal close" indicates that there was a problem that resulted in the connection closing without having performed a close handshake.
552 #### Add close handler
554 The `connection_metadata::on_close` method is added. This method retrieves the close code and reason from the closing handshake and stores it in the local error reason field.
557 void on_close(client * c, websocketpp::connection_hdl hdl) {
559 client::connection_ptr con = c->get_con_from_hdl(hdl);
561 s << "close code: " << con->get_remote_close_code() << " ("
562 << websocketpp::close::status::get_string(con->get_remote_close_code())
563 << "), close reason: " << con->get_remote_close_reason();
564 m_error_reason = s.str();
568 Similarly to `on_open` and `on_fail`, `websocket_endpoint::connect` registers this close handler when a new connection is made.
570 #### Add close method to `websocket_endpoint`
572 This method starts by looking up the given connection ID in the connection list. Next a close request is sent to the connection's handle with the specified WebSocket close code. This is done by calling `endpoint::close`. This is a thread safe method that is used to asynchronously dispatch a close signal to the connection with the given handle. When the operation is complete the connection's close handler will be triggered.
575 void close(int id, websocketpp::close::status::value code) {
576 websocketpp::lib::error_code ec;
578 con_list::iterator metadata_it = m_connection_list.find(id);
579 if (metadata_it == m_connection_list.end()) {
580 std::cout << "> No connection found with id " << id << std::endl;
584 m_endpoint.close(metadata_it->second->get_hdl(), code, "", ec);
586 std::cout << "> Error initiating close: " << ec.message() << std::endl;
591 #### Add close option to the command loop and help message
593 A close option is added to the command loop. It takes a connection ID and optionally a close code and a close reason. If no code is specified the default of 1000/Normal is used. If no reason is specified, none is sent. The `endpoint::close` method will do some error checking and abort the close request if you try and send an invalid code or a reason with invalid UTF8 formatting. Reason strings longer than 125 characters will be truncated.
595 An entry is also added to the help system to describe how the new command may be used.
598 else if (input.substr(0,5) == "close") {
599 std::stringstream ss(input);
603 int close_code = websocketpp::close::status::normal;
606 ss >> cmd >> id >> close_code;
607 std::getline(ss,reason);
609 endpoint.close(id, close_code, reason);
613 #### Close all outstanding connections in `websocket_endpoint` destructor
615 Until now quitting the program left outstanding connections and the WebSocket++ network thread in a lurch. Now that we have a method of closing connections we can clean this up properly.
617 The destructor for `websocket_endpoint` now stops perpetual mode (so the run thread exits after the last connection is closed) and iterates through the list of open connections and requests a clean close for each. Finally, the run thread is joined which causes the program to wait until those connection closes complete.
620 ~websocket_endpoint() {
621 m_endpoint.stop_perpetual();
623 for (con_list::const_iterator it = m_connection_list.begin(); it != m_connection_list.end(); ++it) {
624 if (it->second->get_status() != "Open") {
625 // Only close open connections
629 std::cout << "> Closing connection " << it->second->get_id() << std::endl;
631 websocketpp::lib::error_code ec;
632 m_endpoint.close(it->second->get_hdl(), websocketpp::close::status::going_away, "", ec);
634 std::cout << "> Error closing connection " << it->second->get_id() << ": "
635 << ec.message() << std::endl;
645 There are no changes to the build instructions from step 4
650 Enter Command: connect ws://localhost:9002
651 > Created connection with id 0
652 Enter Command: close 0 1001 example message
653 Enter Command: show 0
654 > URI: ws://localhost:9002
656 > Remote Server: WebSocket++/0.4.0
657 > Error/close reason: close code: 1001 (Going away), close reason: example message
658 Enter Command: connect ws://localhost:9002
659 > Created connection with id 1
660 Enter Command: close 1 1006
661 > Error initiating close: Invalid close code used
663 > Closing connection 1
668 _Sending and receiving messages_
670 This step adds a command to send a message on a given connection and updates the show command to print a transcript of all sent and received messages for that connection.
672 > ##### Terminology: WebSocket message types (opcodes)
673 > WebSocket messages have types indicated by their opcode. The protocol currently specifies two different opcodes for data messages, text and binary. Text messages represent UTF8 text and will be validated as such. Binary messages represent raw binary bytes and are passed through directly with no validation.
675 > WebSocket++ provides the values `websocketpp::frame::opcode::text` and `websocketpp::frame::opcode::binary` that can be used to direct how outgoing messages should be sent and to check how incoming messages are formatted.
677 #### Sending Messages
679 Messages are sent using `endpoint::send`. This is a thread safe method that may be called from anywhere to queue a message for sending on the specified connection. There are three send overloads for use with different scenarios.
681 Each method takes a `connection_hdl` to indicate which connection to send the message on as well as a `frame::opcode::value` to indicate which opcode to label the message as. All overloads are also available with an exception free varient that fills in a a status/error code instead of throwing.
683 The first overload, `connection_hdl hdl, std::string const & payload, frame::opcode::value op`, takes a `std::string`. The string contents are copied into an internal buffer and can be safely modified after calling send.
685 The second overload, `connection_hdl hdl, void const * payload, size_t len, frame::opcode::value op`, takes a void * buffer and length. The buffer contents are copied and can be safely modified after calling send.
687 The third overload, `connection_hdl hdl, message_ptr msg`, takes a WebSocket++ `message_ptr`. This overload allows a message to be constructed in place before the call to send. It also may allow a single message buffer to be sent multiple times, including to multiple connections, without copying. Whether or not this actually happens depends on other factors such as whether compression is enabled. The contents of the message buffer may not be safely modified after being sent.
689 > ###### Terminology: Outgoing WebSocket message queueing & flow control
690 > In many configurations, such as when the Asio based transport is in use, WebSocket++ is an asynchronous system. As such the `endpoint::send` method may return before any bytes are actually written to the outgoing socket. In cases where send is called multiple times in quick succession messages may be coalesced and sent in the same operation or even the same TCP packet. When this happens the message boundaries are preserved (each call to send will produce a separate message).
692 > In the case of applications that call send from inside a handler this means that no messages will be written to the socket until that handler returns. If you are planning to send many messages in this manor or need a message to be written on the wire before continuing you should look into using multiple threads or the built in timer/interrupt handler functionality.
694 > If the outgoing socket link is slow messages may build up in this queue. You can use `connection::get_buffered_amount` to query the current size of the written message queue to decide if you want to change your sending behavior.
696 #### Add send method to `websocket_endpoint`
698 Like the close method, send will start by looking up the given connection ID in the connection list. Next a send request is sent to the connection's handle with the specified WebSocket message and the text opcode. Finally, we record the sent message with our connection metadata object so later our show connection command can print a list of messages sent.
701 void send(int id, std::string message) {
702 websocketpp::lib::error_code ec;
704 con_list::iterator metadata_it = m_connection_list.find(id);
705 if (metadata_it == m_connection_list.end()) {
706 std::cout << "> No connection found with id " << id << std::endl;
710 m_endpoint.send(metadata_it->second->get_hdl(), message, websocketpp::frame::opcode::text, ec);
712 std::cout << "> Error sending message: " << ec.message() << std::endl;
716 metadata_it->second->record_sent_message(message);
720 #### Add send option to the command loop and help message
722 A send option is added to the command loop. It takes a connection ID and a text message to send. An entry is also added to the help system to describe how the new command may be used.
725 else if (input.substr(0,4) == "send") {
726 std::stringstream ss(input);
730 std::string message = "";
733 std::getline(ss,message);
735 endpoint.send(id, message);
739 #### Add glue to `connection_metadata` for storing sent messages
741 In order to store messages sent on this connection some code is added to `connection_metadata`. This includes a new data member `std::vector<std::string> m_messages` to keep track of all messages sent and received as well as a method for adding a sent message in that list:
744 void record_sent_message(std::string message) {
745 m_messages.push_back(">> " + message);
749 Finally the connection metadata output operator is updated to also print a list of processed messages:
752 out << "> Messages Processed: (" << data.m_messages.size() << ") \n";
754 std::vector<std::string>::const_iterator it;
755 for (it = data.m_messages.begin(); it != data.m_messages.end(); ++it) {
760 #### Receiving Messages
762 Messages are received by registering a message handler. This handler will be called once per message received and its signature is `void on_message(websocketpp::connection_hdl hdl, endpoint::message_ptr msg)`. The `connection_hdl`, like the similar parameter from the other handlers is a handle for the connection that the message was received on. The `message_ptr` is a pointer to an object that can be queried for the message payload, opcode, and other metadata. Note that the message_ptr type, as well as its underlying message type, is dependent on how your endpoint is configured and may be different for different configs.
764 #### Add a message handler to method to `connection_metadata`
766 The message receiving behave that we are implementing will be to collect all messages sent and received and to print them in order when the show connection command is run. The sent messages are already being added to that list. Now we add a message handler that pushes received messages to the list as well. Text messages are pushed as-is. Binary messages are first converted to printable hexadecimal format.
769 void on_message(websocketpp::connection_hdl hdl, client::message_ptr msg) {
770 if (msg->get_opcode() == websocketpp::frame::opcode::text) {
771 m_messages.push_back(msg->get_payload());
773 m_messages.push_back(websocketpp::utility::to_hex(msg->get_payload()));
778 In order to have this handler called when new messages are received we also register it with our connection. Note that unlike most other handlers, the message handler has two parameters and thus needs two placeholders.
781 con->set_message_handler(websocketpp::lib::bind(
782 &connection_metadata::on_message,
784 websocketpp::lib::placeholders::_1,
785 websocketpp::lib::placeholders::_2
791 There are no changes to the build instructions from step 5
795 In this example run we are connecting to the WebSocket++ example echo_server. This server will repeat any message we send back to it. You can also try testing this with the echo server at `ws://echo.websocket.org` with similar results.
798 Enter Command: connect ws://localhost:9002
799 > Created connection with id 0
800 Enter Command: send 0 example message
801 Enter Command: show 0
802 > URI: ws://localhost:9002
804 > Remote Server: WebSocket++/0.4.0
805 > Error/close reason: N/A
806 > Messages Processed: (2)
813 _Using TLS / Secure WebSockets_
815 - Change the includes
816 - link to the new library dependencies
818 - add the `tls_init_handler`
819 - configure the SSL context for desired security level
820 - mixing secure and non-secure connections in one application.
822 Chapter 2: Intermediate Features
823 --------------------------------
827 _Intermediate level features_
829 - Subprotocol negotiation
830 - Setting and reading custom headers
835 - Timers and security
837 - Send one message to all connections
840 ### Misc stuff not sure if it should be included here or elsewhere?
842 core websocket++ control flow.
843 A handshake, followed by a split into 2 independent control strands
845 -- use information specified before the call to endpoint::connect to construct a WebSocket handshake request.
846 -- Pass the WebSocket handshake request to the transport policy. The transport policy determines how to get these bytes to the endpoint playing the server role. Depending on which transport policy your endpoint uses this method will be different.
847 -- Receive a handshake response from the underlying transport. This is parsed and checked for conformance to RFC6455. If the validation fails, the fail handler is called. Otherwise the open handler is called.
848 - At this point control splits into two separate strands. One that reads new bytes from the transport policy on the incoming channle, the other that accepts new messages from the local application for framing and writing to the outgoing transport channel.
850 -- Read and process new bytes from transport
851 -- If the bytes contain at least one complete message dispatch each message by calling the appropriate handler. This is either the message handler for data messages, or ping/pong/close handlers for each respective control message. If no handler is registered for a particular message it is ignored.
852 -- Ask the transport layer for more bytes
854 -- Wait for messages from the application
855 -- Perform error checking on message input,
856 -- Frame message per RFC6455
857 -- Queue message for sending
858 -- Pass all outstanding messages to the transport policy for output
859 -- When there are no messages left to send, return to waiting
861 Important observations
862 Handlers run in line with library processing which has several implications applications should be aware of: