Echoes back all received WebSocket messages
| 32 | |
| 33 | // Echoes back all received WebSocket messages |
| 34 | void |
| 35 | do_session(tcp::socket socket) |
| 36 | { |
| 37 | try |
| 38 | { |
| 39 | // Construct the stream by moving in the socket |
| 40 | websocket::stream<tcp::socket> ws{std::move(socket)}; |
| 41 | |
| 42 | // Set a decorator to change the Server of the handshake |
| 43 | ws.set_option(websocket::stream_base::decorator( |
| 44 | [](websocket::response_type& res) |
| 45 | { |
| 46 | res.set(http::field::server, |
| 47 | std::string(BOOST_BEAST_VERSION_STRING) + |
| 48 | " websocket-server-sync"); |
| 49 | })); |
| 50 | |
| 51 | // Accept the websocket handshake |
| 52 | ws.accept(); |
| 53 | |
| 54 | for(;;) |
| 55 | { |
| 56 | // This buffer will hold the incoming message |
| 57 | beast::flat_buffer buffer; |
| 58 | |
| 59 | // Read a message |
| 60 | ws.read(buffer); |
| 61 | |
| 62 | // Echo the message back |
| 63 | ws.text(ws.got_text()); |
| 64 | ws.write(buffer.data()); |
| 65 | } |
| 66 | } |
| 67 | catch(beast::system_error const& se) |
| 68 | { |
| 69 | // This indicates that the session was closed |
| 70 | if(se.code() != websocket::error::closed) |
| 71 | std::cerr << "Error: " << se.code().message() << std::endl; |
| 72 | } |
| 73 | catch(std::exception const& e) |
| 74 | { |
| 75 | std::cerr << "Error: " << e.what() << std::endl; |
| 76 | } |
| 77 | } |
| 78 | |
| 79 | //------------------------------------------------------------------------------ |
| 80 |