websocket_session.hpp 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. //
  2. // Copyright (c) 2016-2019 Vinnie Falco (vinnie dot falco at gmail dot com)
  3. //
  4. // Distributed under the Boost Software License, Version 1.0. (See accompanying
  5. // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  6. //
  7. // Official repository: https://github.com/vinniefalco/CppCon2018
  8. //
  9. #ifndef BOOST_BEAST_EXAMPLE_WEBSOCKET_CHAT_MULTI_WEBSOCKET_SESSION_HPP
  10. #define BOOST_BEAST_EXAMPLE_WEBSOCKET_CHAT_MULTI_WEBSOCKET_SESSION_HPP
  11. #include "net.hpp"
  12. #include "beast.hpp"
  13. #include "shared_state.hpp"
  14. #include <cstdlib>
  15. #include <memory>
  16. #include <string>
  17. #include <vector>
  18. // Forward declaration
  19. class shared_state;
  20. /** Represents an active WebSocket connection to the server
  21. */
  22. class websocket_session : public boost::enable_shared_from_this<websocket_session>
  23. {
  24. beast::flat_buffer buffer_;
  25. websocket::stream<beast::tcp_stream> ws_;
  26. boost::shared_ptr<shared_state> state_;
  27. std::vector<boost::shared_ptr<std::string const>> queue_;
  28. void fail(beast::error_code ec, char const* what);
  29. void on_accept(beast::error_code ec);
  30. void on_read(beast::error_code ec, std::size_t bytes_transferred);
  31. void on_write(beast::error_code ec, std::size_t bytes_transferred);
  32. public:
  33. websocket_session(
  34. tcp::socket&& socket,
  35. boost::shared_ptr<shared_state> const& state);
  36. ~websocket_session();
  37. template<class Body, class Allocator>
  38. void
  39. run(http::request<Body, http::basic_fields<Allocator>> req);
  40. // Send a message
  41. void
  42. send(boost::shared_ptr<std::string const> const& ss);
  43. private:
  44. void
  45. on_send(boost::shared_ptr<std::string const> const& ss);
  46. };
  47. template<class Body, class Allocator>
  48. void
  49. websocket_session::
  50. run(http::request<Body, http::basic_fields<Allocator>> req)
  51. {
  52. // Set suggested timeout settings for the websocket
  53. ws_.set_option(
  54. websocket::stream_base::timeout::suggested(
  55. beast::role_type::server));
  56. // Set a decorator to change the Server of the handshake
  57. ws_.set_option(websocket::stream_base::decorator(
  58. [](websocket::response_type& res)
  59. {
  60. res.set(http::field::server,
  61. std::string(BOOST_BEAST_VERSION_STRING) +
  62. " websocket-chat-multi");
  63. }));
  64. // Accept the websocket handshake
  65. ws_.async_accept(
  66. req,
  67. beast::bind_front_handler(
  68. &websocket_session::on_accept,
  69. shared_from_this()));
  70. }
  71. #endif