Branch data Line data Source code
1 : : #pragma once 2 : : 3 : : #include <boost/asio/ip/tcp.hpp> 4 : : #include <boost/beast/core.hpp> 5 : : #include <boost/beast/websocket.hpp> 6 : : #include <functional> 7 : : #include <string> 8 : : 9 : : 10 : : namespace m { 11 : : 12 : : 13 : : struct WebSocketServer 14 : : { 15 : : using on_message_t = std::function<void(std::string)>; 16 : : using web_socket_t = boost::beast::websocket::stream<boost::asio::ip::tcp::socket>; 17 : : 18 : : struct Connection 19 : : { 20 : : private: 21 : : WebSocketServer &server_; 22 : : std::unique_ptr<web_socket_t> ws_; 23 : : 24 : : public: 25 : : Connection(WebSocketServer &server, std::unique_ptr<web_socket_t> ws); 26 : : Connection(const Connection&) = delete; 27 : 0 : Connection(Connection&&) = default; 28 : : 29 : 0 : WebSocketServer & server() const { return server_; } 30 : : web_socket_t & ws() const { return *ws_; } 31 : : 32 : : void send(std::string_view msg); 33 : : void listen(); 34 : : bool wait_on_message(); 35 : : }; 36 : : 37 : : private: 38 : : boost::asio::io_context io_ctx_; 39 : : boost::asio::ip::tcp::acceptor acceptor_; 40 : : on_message_t on_message_; 41 : : uint16_t port_; 42 : : 43 : : public: 44 : : WebSocketServer(uint16_t port, on_message_t onMessage); 45 : : WebSocketServer(const WebSocketServer&) = delete; 46 : : 47 : : uint16_t port() const { return port_; } 48 [ # # ]: 0 : void on_message(std::string str) { on_message_(str); } 49 : : 50 : : Connection await(); 51 : : }; 52 : : 53 : : }