fixed adding file problem
[c11concurrency-benchmarks.git] / gdax-orderbook-hpp / demo / dependencies / websocketpp-0.7.0 / examples / associative_storage / associative_storage.cpp
1 #include <iostream>
2 #include <map>
3 #include <exception>
4 #include <websocketpp/config/asio_no_tls.hpp>
5 #include <websocketpp/server.hpp>
6
7 typedef websocketpp::server<websocketpp::config::asio> server;
8
9 using websocketpp::connection_hdl;
10 using websocketpp::lib::placeholders::_1;
11 using websocketpp::lib::placeholders::_2;
12 using websocketpp::lib::bind;
13
14 struct connection_data {
15     int sessionid;
16     std::string name;
17 };
18
19 class print_server {
20 public:
21     print_server() : m_next_sessionid(1) {
22         m_server.init_asio();
23
24         m_server.set_open_handler(bind(&print_server::on_open,this,::_1));
25         m_server.set_close_handler(bind(&print_server::on_close,this,::_1));
26         m_server.set_message_handler(bind(&print_server::on_message,this,::_1,::_2));
27     }
28
29     void on_open(connection_hdl hdl) {
30         connection_data data;
31
32         data.sessionid = m_next_sessionid++;
33         data.name.clear();
34
35         m_connections[hdl] = data;
36     }
37
38     void on_close(connection_hdl hdl) {
39         connection_data& data = get_data_from_hdl(hdl);
40
41         std::cout << "Closing connection " << data.name
42                   << " with sessionid " << data.sessionid << std::endl;
43
44         m_connections.erase(hdl);
45     }
46
47     void on_message(connection_hdl hdl, server::message_ptr msg) {
48         connection_data& data = get_data_from_hdl(hdl);
49
50         if (data.name.empty()) {
51             data.name = msg->get_payload();
52             std::cout << "Setting name of connection with sessionid "
53                       << data.sessionid << " to " << data.name << std::endl;
54         } else {
55             std::cout << "Got a message from connection " << data.name
56                       << " with sessionid " << data.sessionid << std::endl;
57         }
58     }
59
60     connection_data& get_data_from_hdl(connection_hdl hdl) {
61         auto it = m_connections.find(hdl);
62
63         if (it == m_connections.end()) {
64             // this connection is not in the list. This really shouldn't happen
65             // and probably means something else is wrong.
66             throw std::invalid_argument("No data available for session");
67         }
68
69         return it->second;
70     }
71
72     void run(uint16_t port) {
73         m_server.listen(port);
74         m_server.start_accept();
75         m_server.run();
76     }
77 private:
78     typedef std::map<connection_hdl,connection_data,std::owner_less<connection_hdl>> con_list;
79
80     int m_next_sessionid;
81     server m_server;
82     con_list m_connections;
83 };
84
85 int main() {
86     print_server server;
87     server.run(9002);
88 }