WebSocket++  0.8.0-dev
C++ websocket client/server library
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Pages
simple_count_server_thread.cpp
1 #include <functional>
2 #include <mutex>
3 #include <set>
4 #include <thread>
5 
6 #include <websocketpp/config/asio_no_tls.hpp>
7 #include <websocketpp/server.hpp>
8 
9 typedef websocketpp::server<websocketpp::config::asio> server;
10 
11 using websocketpp::connection_hdl;
12 
13 class count_server {
14 public:
15  count_server() : m_count(0) {
16  m_server.init_asio();
17 
18  m_server.set_open_handler(bind(&count_server::on_open,this,_1));
19  m_server.set_close_handler(bind(&count_server::on_close,this,_1));
20  }
21 
22  void on_open(connection_hdl hdl) {
23  std::lock_guard<std::mutex> lock(m_mutex);
24  m_connections.insert(hdl);
25  }
26 
27  void on_close(connection_hdl hdl) {
28  std::lock_guard<std::mutex> lock(m_mutex);
29  m_connections.erase(hdl);
30  }
31 
32  void count() {
33  while (1) {
34  sleep(1);
35  m_count++;
36 
37  std::stringstream ss;
38  ss << m_count;
39 
40  std::lock_guard<std::mutex> lock(m_mutex);
41  for (auto it : m_connections) {
42  m_server.send(it,ss.str(),websocketpp::frame::opcode::text);
43  }
44  }
45  }
46 
47  void run(uint16_t port) {
48  m_server.listen(port);
49  m_server.start_accept();
50  m_server.run();
51  }
52 private:
53  typedef std::set<connection_hdl,std::owner_less<connection_hdl>> con_list;
54 
55  int m_count;
56  server m_server;
57  con_list m_connections;
58  std::mutex m_mutex;
59 };
60 
61 int main() {
62  count_server server;
63  std::thread t(std::bind(&count_server::count,&server));
64  server.run(9002);
65 }