fixed adding file problem
[c11concurrency-benchmarks.git] / gdax-orderbook-hpp / demo / dependencies / websocketpp-0.7.0 / tutorials / utility_client / utility_client.md
1 Utility Client Example Application Tutorial
2 ===========================================
3
4 Chapter 1: Initial Setup & Basics
5 ---------------------------------
6
7 Setting up the basic types, opening and closing connections, sending and receiving messages.
8
9 ### Step 1
10
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.
12
13 #### Build
14 `clang++ step1.cpp`
15
16 #### Code so far
17
18 *note* A code snapshot for each step is present next to this tutorial file in the git repository.
19
20 ~~~{.cpp}
21 #include <iostream>
22 #include <string>
23
24 int main() {
25     bool done = false;
26     std::string input;
27
28     while (!done) {
29         std::cout << "Enter Command: ";
30         std::getline(std::cin, input);
31
32         if (input == "quit") {
33             done = true;
34         } else if (input == "help") {
35             std::cout
36                 << "\nCommand List:\n"
37                 << "help: Display this help text\n"
38                 << "quit: Exit the program\n"
39                 << std::endl;
40         } else {
41             std::cout << "Unrecognized Command" << std::endl;
42         }
43     }
44
45     return 0;
46 }
47 ~~~
48
49 ### Step 2
50
51 _Add WebSocket++ includes and set up an endpoint type._
52
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.
56
57 The connection stores information specific to each WebSocket session.
58
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.
61
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.
63
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.
66
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.
68
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.
70
71 `typedef websocketpp::client<websocketpp::config::asio_client> client`
72
73 #### Build
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.
75
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.
77
78 `clang++ step2.cpp -lboost_system`
79
80 #### Code so far
81 ~~~{.cpp}
82 #include <websocketpp/config/asio_no_tls_client.hpp>
83 #include <websocketpp/client.hpp>
84
85 #include <iostream>
86 #include <string>
87
88 typedef websocketpp::client<websocketpp::config::asio_client> client;
89
90 int main() {
91     bool done = false;
92     std::string input;
93
94     while (!done) {
95         std::cout << "Enter Command: ";
96         std::getline(std::cin, input);
97
98         if (input == "quit") {
99             done = true;
100         } else if (input == "help") {
101             std::cout
102                 << "\nCommand List:\n"
103                 << "help: Display this help text\n"
104                 << "quit: Exit the program\n"
105                 << std::endl;
106         } else {
107             std::cout << "Unrecognized Command" << std::endl;
108         }
109     }
110
111     return 0;
112 }
113 ~~~
114
115 ### Step 3
116
117 _Create endpoint wrapper object that handles initialization and setting up the background thread._
118
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.
120
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.
123 >
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.
125 >
126 >[TODO: link to more information about websocketpp::lib namespace and C++11 setup]
127
128 Within the `websocket_endpoint` constructor several things happen:
129
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]
131 ~~~{.cpp}
132 m_endpoint.clear_access_channels(websocketpp::log::alevel::all);
133 m_endpoint.clear_error_channels(websocketpp::log::elevel::all);
134 ~~~
135
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.
137 ~~~{.cpp}
138 m_endpoint.init_asio();
139 m_endpoint.start_perpetual();
140 ~~~
141
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.
143 ~~~{.cpp}
144 m_thread.reset(new websocketpp::lib::thread(&client::run, &m_endpoint));
145 ~~~
146
147 #### Build
148
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`.
150
151 ##### Clang (C++98 & boost)
152 `clang++ step3.cpp -lboost_system -lboost_random -lboost_thread`
153
154 ##### Clang (C++11)
155 `clang++ -std=c++0x -stdlib=libc++ step3.cpp -lboost_system -D_WEBSOCKETPP_CPP11_STL_`
156
157 ##### G++ (C++98 & Boost)
158 `g++ step3.cpp -lboost_system -lboost_random -lboost_thread`
159
160 ##### G++ v4.6+ (C++11)
161 `g++ -std=c++0x step3.cpp -lboost_system -D_WEBSOCKETPP_CPP11_STL_`
162
163 #### Code so far
164
165 ~~~{.cpp}
166 #include <websocketpp/config/asio_no_tls_client.hpp>
167 #include <websocketpp/client.hpp>
168
169 #include <websocketpp/common/thread.hpp>
170 #include <websocketpp/common/memory.hpp>
171
172 #include <iostream>
173 #include <string>
174
175 typedef websocketpp::client<websocketpp::config::asio_client> client;
176
177 class websocket_endpoint {
178 public:
179     websocket_endpoint () {
180         m_endpoint.clear_access_channels(websocketpp::log::alevel::all);
181         m_endpoint.clear_error_channels(websocketpp::log::elevel::all);
182
183         m_endpoint.init_asio();
184         m_endpoint.start_perpetual();
185
186         m_thread.reset(new websocketpp::lib::thread(&client::run, &m_endpoint));
187     }
188 private:
189     client m_endpoint;
190     websocketpp::lib::shared_ptr<websocketpp::lib::thread> m_thread;
191 };
192
193 int main() {
194     bool done = false;
195     std::string input;
196     websocket_endpoint endpoint;
197
198     while (!done) {
199         std::cout << "Enter Command: ";
200         std::getline(std::cin, input);
201
202         if (input == "quit") {
203             done = true;
204         } else if (input == "help") {
205             std::cout
206                 << "\nCommand List:\n"
207                 << "help: Display this help text\n"
208                 << "quit: Exit the program\n"
209                 << std::endl;
210         } else {
211             std::cout << "Unrecognized Command" << std::endl;
212         }
213     }
214
215     return 0;
216 }
217 ~~~
218
219 ### Step 4
220
221 _Opening WebSocket connections_
222
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.
224
225 #### New Connection Metadata Object
226
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.
228
229 #### Update `websocket_endpoint`
230
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.
232
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.
235
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.
238 >
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.
242
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.
245 >
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.
247 >
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.
250 >
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?]
256
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.
258
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.
261 >
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.
264 >
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.
266
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.
268
269 ~~~{.cpp}
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;
273 ~~~
274
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).
276
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.
279 >
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.
281 >
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.
283 >
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.
285 >
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.
287
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.
289
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.
291
292 Lets look at the parameters being sent to bind in detail:
293
294 ~~~{.cpp}
295 con->set_open_handler(websocketpp::lib::bind(
296     &connection_metadata::on_open,
297     metadata,
298     &m_endpoint,
299     websocketpp::lib::placeholders::_1
300 ));
301 ~~~
302
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.
304
305 Finally, we call `endpoint::connect()` on our configured connection request and return the new connection ID.
306
307 #### Handler Member Functions
308
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.
310
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.
312
313 #### New Commands
314
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.
316
317 ~~~{.cpp}
318 } else if (input.substr(0,7) == "connect") {
319     int id = endpoint.connect(input.substr(8));
320     if (id != -1) {
321         std::cout << "> Created connection with id " << id << std::endl;
322     }
323 } else if (input.substr(0,4) == "show") {
324     int id = atoi(input.substr(5).c_str());
325
326     connection_metadata::ptr metadata = endpoint.get_metadata(id);
327     if (metadata) {
328         std::cout << *metadata << std::endl;
329     } else {
330         std::cout << "> Unknown connection id " << id << std::endl;
331     }
332 }
333 ~~~
334
335 #### Build
336
337 There are no changes to the build instructions from step 3
338
339 #### Run
340
341 ~~~
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
350 > Status: Open
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
357 > Status: Failed
358 > Remote Server: Apache
359 > Error/close reason: Invalid HTTP status.
360 ~~~
361
362 #### Code so far
363
364 ~~~{.cpp}
365 #include <websocketpp/config/asio_no_tls_client.hpp>
366 #include <websocketpp/client.hpp>
367
368 #include <websocketpp/common/thread.hpp>
369 #include <websocketpp/common/memory.hpp>
370
371 #include <cstdlib>
372 #include <iostream>
373 #include <map>
374 #include <string>
375 #include <sstream>
376
377 typedef websocketpp::client<websocketpp::config::asio_client> client;
378
379 class connection_metadata {
380 public:
381     typedef websocketpp::lib::shared_ptr<connection_metadata> ptr;
382
383     connection_metadata(int id, websocketpp::connection_hdl hdl, std::string uri)
384       : m_id(id)
385       , m_hdl(hdl)
386       , m_status("Connecting")
387       , m_uri(uri)
388       , m_server("N/A")
389     {}
390
391     void on_open(client * c, websocketpp::connection_hdl hdl) {
392         m_status = "Open";
393
394         client::connection_ptr con = c->get_con_from_hdl(hdl);
395         m_server = con->get_response_header("Server");
396     }
397
398     void on_fail(client * c, websocketpp::connection_hdl hdl) {
399         m_status = "Failed";
400
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();
404     }
405
406     friend std::ostream & operator<< (std::ostream & out, connection_metadata const & data);
407 private:
408     int m_id;
409     websocketpp::connection_hdl m_hdl;
410     std::string m_status;
411     std::string m_uri;
412     std::string m_server;
413     std::string m_error_reason;
414 };
415
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);
421
422     return out;
423 }
424
425 class websocket_endpoint {
426 public:
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);
430
431         m_endpoint.init_asio();
432         m_endpoint.start_perpetual();
433
434         m_thread.reset(new websocketpp::lib::thread(&client::run, &m_endpoint));
435     }
436
437     int connect(std::string const & uri) {
438         websocketpp::lib::error_code ec;
439
440         client::connection_ptr con = m_endpoint.get_connection(uri, ec);
441
442         if (ec) {
443             std::cout << "> Connect initialization error: " << ec.message() << std::endl;
444             return -1;
445         }
446
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;
450
451         con->set_open_handler(websocketpp::lib::bind(
452             &connection_metadata::on_open,
453             metadata_ptr,
454             &m_endpoint,
455             websocketpp::lib::placeholders::_1
456         ));
457         con->set_fail_handler(websocketpp::lib::bind(
458             &connection_metadata::on_fail,
459             metadata_ptr,
460             &m_endpoint,
461             websocketpp::lib::placeholders::_1
462         ));
463
464         m_endpoint.connect(con);
465
466         return new_id;
467     }
468
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();
473         } else {
474             return metadata_it->second;
475         }
476     }
477 private:
478     typedef std::map<int,connection_metadata::ptr> con_list;
479
480     client m_endpoint;
481     websocketpp::lib::shared_ptr<websocketpp::lib::thread> m_thread;
482
483     con_list m_connection_list;
484     int m_next_id;
485 };
486
487 int main() {
488     bool done = false;
489     std::string input;
490     websocket_endpoint endpoint;
491
492     while (!done) {
493         std::cout << "Enter Command: ";
494         std::getline(std::cin, input);
495
496         if (input == "quit") {
497             done = true;
498         } else if (input == "help") {
499             std::cout
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"
505                 << std::endl;
506         } else if (input.substr(0,7) == "connect") {
507             int id = endpoint.connect(input.substr(8));
508             if (id != -1) {
509                 std::cout << "> Created connection with id " << id << std::endl;
510             }
511         } else if (input.substr(0,4) == "show") {
512             int id = atoi(input.substr(5).c_str());
513
514             connection_metadata::ptr metadata = endpoint.get_metadata(id);
515             if (metadata) {
516                 std::cout << *metadata << std::endl;
517             } else {
518                 std::cout << "> Unknown connection id " << id << std::endl;
519             }
520         } else {
521             std::cout << "> Unrecognized Command" << std::endl;
522         }
523     }
524
525     return 0;
526 }
527 ~~~
528
529 ### Step 5
530
531 _Closing connections_
532
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.
534
535 #### Getting connection close information out of WebSocket++
536
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
539
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.
541
542 During the close handler call WebSocket++ connections offer the following methods for accessing close handshake information:
543
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.
549
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.
551
552 #### Add close handler
553
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.
555
556 ~~~{.cpp}
557 void on_close(client * c, websocketpp::connection_hdl hdl) {
558     m_status = "Closed";
559     client::connection_ptr con = c->get_con_from_hdl(hdl);
560     std::stringstream s;
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();
565 }
566 ~~~
567
568 Similarly to `on_open` and `on_fail`, `websocket_endpoint::connect` registers this close handler when a new connection is made.
569
570 #### Add close method to `websocket_endpoint`
571
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.
573
574 ~~~{.cpp}
575 void close(int id, websocketpp::close::status::value code) {
576     websocketpp::lib::error_code ec;
577     
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;
581         return;
582     }
583     
584     m_endpoint.close(metadata_it->second->get_hdl(), code, "", ec);
585     if (ec) {
586         std::cout << "> Error initiating close: " << ec.message() << std::endl;
587     }
588 }
589 ~~~
590
591 #### Add close option to the command loop and help message
592
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.
594
595 An entry is also added to the help system to describe how the new command may be used.
596
597 ~~~{.cpp}
598 else if (input.substr(0,5) == "close") {
599     std::stringstream ss(input);
600     
601     std::string cmd;
602     int id;
603     int close_code = websocketpp::close::status::normal;
604     std::string reason;
605     
606     ss >> cmd >> id >> close_code;
607     std::getline(ss,reason);
608     
609     endpoint.close(id, close_code, reason);
610 }
611 ~~~
612
613 #### Close all outstanding connections in `websocket_endpoint` destructor
614
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.
616
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.
618
619 ~~~{.cpp}
620 ~websocket_endpoint() {
621     m_endpoint.stop_perpetual();
622     
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
626             continue;
627         }
628         
629         std::cout << "> Closing connection " << it->second->get_id() << std::endl;
630         
631         websocketpp::lib::error_code ec;
632         m_endpoint.close(it->second->get_hdl(), websocketpp::close::status::going_away, "", ec);
633         if (ec) {
634             std::cout << "> Error closing connection " << it->second->get_id() << ": "  
635                       << ec.message() << std::endl;
636         }
637     }
638     
639     m_thread->join();
640 }
641 ~~~
642
643 #### Build
644
645 There are no changes to the build instructions from step 4
646
647 #### Run
648
649 ~~~
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
655 > Status: Closed
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
662 Enter Command: quit
663 > Closing connection 1
664 ~~~
665
666 ### Step 6
667
668 _Sending and receiving messages_
669
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.
671
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. 
674 >
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.
676
677 #### Sending Messages
678
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. 
680
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.
682
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.
684
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.
686
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.
688
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).
691 >
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.
693 >
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.
695
696 #### Add send method to `websocket_endpoint`
697
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.
699
700 ~~~{.cpp}
701 void send(int id, std::string message) {
702     websocketpp::lib::error_code ec;
703     
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;
707         return;
708     }
709     
710     m_endpoint.send(metadata_it->second->get_hdl(), message, websocketpp::frame::opcode::text, ec);
711     if (ec) {
712         std::cout << "> Error sending message: " << ec.message() << std::endl;
713         return;
714     }
715     
716     metadata_it->second->record_sent_message(message);
717 }
718 ~~~
719
720 #### Add send option to the command loop and help message
721
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.
723
724 ~~~{.cpp}
725 else if (input.substr(0,4) == "send") {
726     std::stringstream ss(input);
727         
728         std::string cmd;
729         int id;
730         std::string message = "";
731         
732         ss >> cmd >> id;
733         std::getline(ss,message);
734         
735         endpoint.send(id, message);
736 }
737 ~~~
738
739 #### Add glue to `connection_metadata` for storing sent messages
740
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:
742
743 ~~~{.cpp}
744 void record_sent_message(std::string message) {
745     m_messages.push_back(">> " + message);
746 }
747 ~~~
748
749 Finally the connection metadata output operator is updated to also print a list of processed messages:
750
751 ~~~{.cpp}
752 out << "> Messages Processed: (" << data.m_messages.size() << ") \n";
753
754 std::vector<std::string>::const_iterator it;
755 for (it = data.m_messages.begin(); it != data.m_messages.end(); ++it) {
756     out << *it << "\n";
757 }
758 ~~~
759
760 #### Receiving Messages
761
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.
763
764 #### Add a message handler to method to `connection_metadata`
765
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.
767
768 ~~~{.cpp}
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());
772     } else {
773         m_messages.push_back(websocketpp::utility::to_hex(msg->get_payload()));
774     }
775 }
776 ~~~
777
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.
779
780 ~~~{.cpp}
781 con->set_message_handler(websocketpp::lib::bind(
782     &connection_metadata::on_message,
783     metadata_ptr,
784     websocketpp::lib::placeholders::_1,
785     websocketpp::lib::placeholders::_2
786 ));
787 ~~~
788
789 #### Build
790
791 There are no changes to the build instructions from step 5
792
793 #### Run
794
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.
796
797 ~~~
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
803 > Status: Open
804 > Remote Server: WebSocket++/0.4.0
805 > Error/close reason: N/A
806 > Messages Processed: (2)
807 >>  example message
808 <<  example message
809 ~~~
810
811 ### Step 7
812
813 _Using TLS / Secure WebSockets_
814
815 - Change the includes
816 - link to the new library dependencies
817 - Switch the config
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.
821
822 Chapter 2: Intermediate Features
823 --------------------------------
824
825 ### Step 8
826
827 _Intermediate level features_
828
829 - Subprotocol negotiation
830 - Setting and reading custom headers
831 - Ping and Pong
832 - Proxies?
833 - Setting user agent
834 - Setting Origin
835 - Timers and security
836 - Close behavior
837 - Send one message to all connections
838
839
840 ### Misc stuff not sure if it should be included here or elsewhere?
841
842 core websocket++ control flow.
843 A handshake, followed by a split into 2 independent control strands
844 - Handshake
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.
849 - Read strand
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
853 - Write strand
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
860
861 Important observations
862 Handlers run in line with library processing which has several implications applications should be aware of: