OSSIA
Open Scenario System for Interactive Application
websocket.hpp
1 #pragma once
2 #include <ossia/network/sockets/configuration.hpp>
3 #include <ossia/network/sockets/websocket_client.hpp>
4 #include <ossia/network/sockets/websocket_server.hpp>
5 
6 #include <boost/asio/write.hpp>
7 /*
8 #include <boost/asio/connect.hpp>
9 #include <boost/asio/ip/tcp.hpp>
10 #include <boost/beast/core.hpp>
11 #include <boost/beast/websocket.hpp>
12 */
14 
15 namespace ossia::net
16 {
17 struct websocket_simple_client : websocket_client
18 {
19  websocket_simple_client(
20  const ws_client_configuration& conf, boost::asio::io_context& ctx)
21  : ossia::net::websocket_client{}
22  , m_host{conf.url}
23  {
24  m_client->init_asio(&ctx);
25  }
26 
27  void connect() { }
28 
29  template <typename F>
30  void receive(F onMessage)
31  {
32 
33  std::weak_ptr<client_t> weak_client = m_client;
34  m_client->set_message_handler(
35  [handler = std::move(onMessage),
36  weak_client](connection_handler hdl, client_t::message_ptr msg) {
37  if(!weak_client.lock())
38  return;
39  const auto& data = msg->get_raw_payload();
40  handler((const unsigned char*)data.data(), data.size());
41  });
42 
43  websocket_client::connect(m_host);
44  }
45 
46  void write(const char* data, std::size_t sz)
47  {
48  send_binary_message(std::string_view{data, sz});
49  }
50 
51  void close()
52  {
53  if(connected())
54  {
55  m_client->get_io_service().post([this] { websocket_client::stop(); });
56  }
57  }
58 
59  std::string m_host;
60 };
61 
62 struct websocket_simple_server : ossia::net::websocket_server
63 {
64  websocket_simple_server(
65  const ws_server_configuration& conf, boost::asio::io_context& ctx)
66  : ossia::net::websocket_server{ctx}
67  , m_port{conf.port}
68  {
69  set_open_handler(
70  [this](connection_handler hdl) { m_listeners.push_back(hdl.lock()); });
71  set_close_handler([this](connection_handler hdl) {
72  ossia::remove_erase(m_listeners, hdl.lock());
73  });
74  }
75 
76  template <typename F>
77  void listen(F onMessage)
78  {
79  m_server.set_message_handler([handler = std::move(onMessage)](
80  connection_handler hdl, server_t::message_ptr msg) {
81  const auto& data = msg->get_raw_payload();
82  handler((const unsigned char*)data.data(), data.size());
83  });
84 
85  websocket_server::listen(m_port);
86  }
87 
88  void write(const char* data, std::size_t sz)
89  {
90  std::string_view dat{data, sz};
91  for(auto& listener : m_listeners)
92  send_binary_message(listener, dat);
93  }
94 
95  void close()
96  {
97  m_server.get_io_service().post([this] { stop(); });
98  }
99 
100  std::vector<std::shared_ptr<void>> m_listeners;
101  int m_port{};
102 };
103 
104 }
Low-level websocket & http server for oscquery.
Definition: websocket_server.hpp:20
Definition: git_info.h:7