websocket.hpp 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. //
  2. // Copyright (c) 2023-2025 Ivica Siladic, Bruno Iljazovic, Korina Simicevic
  3. //
  4. // Distributed under the Boost Software License, Version 1.0.
  5. // (See accompanying file LICENSE or copy at http://www.boost.org/LICENSE_1_0.txt)
  6. //
  7. #ifndef BOOST_MQTT5_WEBSOCKET_HPP
  8. #define BOOST_MQTT5_WEBSOCKET_HPP
  9. #include <boost/mqtt5/detail/async_traits.hpp>
  10. #include <boost/mqtt5/detail/shutdown.hpp>
  11. #include <boost/mqtt5/types.hpp>
  12. #include <boost/beast/http/field.hpp>
  13. #include <boost/beast/websocket/rfc6455.hpp>
  14. #include <boost/beast/websocket/stream.hpp>
  15. namespace boost::mqtt5 {
  16. // Trait definition for Beast
  17. template <typename Stream>
  18. struct ws_handshake_traits<boost::beast::websocket::stream<Stream>> {
  19. template <typename CompletionToken>
  20. static decltype(auto) async_handshake(
  21. boost::beast::websocket::stream<Stream>& stream,
  22. authority_path ap, CompletionToken&& token
  23. ) {
  24. using namespace boost::beast;
  25. // Set suggested timeout settings for the websocket
  26. stream.set_option(
  27. websocket::stream_base::timeout::suggested(role_type::client)
  28. );
  29. stream.binary(true);
  30. // Set a decorator to change the User-Agent of the handshake
  31. stream.set_option(websocket::stream_base::decorator(
  32. [](websocket::request_type& req) {
  33. req.set(http::field::sec_websocket_protocol, "mqtt");
  34. req.set(http::field::user_agent, "boost.mqtt");
  35. })
  36. );
  37. stream.async_handshake(
  38. ap.host + ':' + ap.port, ap.path,
  39. std::forward<CompletionToken>(token)
  40. );
  41. }
  42. };
  43. namespace detail {
  44. // in namespace boost::mqtt5::detail to enable ADL
  45. template <typename Stream, typename ShutdownHandler>
  46. void async_shutdown(
  47. boost::beast::websocket::stream<Stream>& stream, ShutdownHandler&& handler
  48. ) {
  49. stream.async_close(
  50. beast::websocket::close_code::normal,
  51. std::move(handler)
  52. );
  53. }
  54. } // end namespace detail
  55. } // end namespace boost::mqtt5
  56. #endif // !BOOST_MQTT5_WEBSOCKET_HPP