websocket_server_coro_ssl.cpp 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  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/boostorg/beast
  8. //
  9. //------------------------------------------------------------------------------
  10. //
  11. // Example: WebSocket SSL server, coroutine
  12. //
  13. //------------------------------------------------------------------------------
  14. #include "example/common/server_certificate.hpp"
  15. #include <boost/beast/core.hpp>
  16. #include <boost/beast/ssl.hpp>
  17. #include <boost/beast/websocket.hpp>
  18. #include <boost/beast/websocket/ssl.hpp>
  19. #include <boost/asio/spawn.hpp>
  20. #include <algorithm>
  21. #include <cstdlib>
  22. #include <functional>
  23. #include <iostream>
  24. #include <memory>
  25. #include <string>
  26. #include <thread>
  27. #include <vector>
  28. namespace beast = boost::beast; // from <boost/beast.hpp>
  29. namespace http = beast::http; // from <boost/beast/http.hpp>
  30. namespace websocket = beast::websocket; // from <boost/beast/websocket.hpp>
  31. namespace net = boost::asio; // from <boost/asio.hpp>
  32. namespace ssl = boost::asio::ssl; // from <boost/asio/ssl.hpp>
  33. using tcp = boost::asio::ip::tcp; // from <boost/asio/ip/tcp.hpp>
  34. //------------------------------------------------------------------------------
  35. // Report a failure
  36. void
  37. fail(beast::error_code ec, char const* what)
  38. {
  39. std::cerr << what << ": " << ec.message() << "\n";
  40. }
  41. // Echoes back all received WebSocket messages
  42. void
  43. do_session(
  44. websocket::stream<
  45. beast::ssl_stream<beast::tcp_stream>>& ws,
  46. net::yield_context yield)
  47. {
  48. beast::error_code ec;
  49. // Set the timeout.
  50. beast::get_lowest_layer(ws).expires_after(std::chrono::seconds(30));
  51. // Perform the SSL handshake
  52. ws.next_layer().async_handshake(ssl::stream_base::server, yield[ec]);
  53. if(ec)
  54. return fail(ec, "handshake");
  55. // Turn off the timeout on the tcp_stream, because
  56. // the websocket stream has its own timeout system.
  57. beast::get_lowest_layer(ws).expires_never();
  58. // Set suggested timeout settings for the websocket
  59. ws.set_option(
  60. websocket::stream_base::timeout::suggested(
  61. beast::role_type::server));
  62. // Set a decorator to change the Server of the handshake
  63. ws.set_option(websocket::stream_base::decorator(
  64. [](websocket::response_type& res)
  65. {
  66. res.set(http::field::server,
  67. std::string(BOOST_BEAST_VERSION_STRING) +
  68. " websocket-server-coro-ssl");
  69. }));
  70. // Accept the websocket handshake
  71. ws.async_accept(yield[ec]);
  72. if(ec)
  73. return fail(ec, "accept");
  74. for(;;)
  75. {
  76. // This buffer will hold the incoming message
  77. beast::flat_buffer buffer;
  78. // Read a message
  79. ws.async_read(buffer, yield[ec]);
  80. // This indicates that the session was closed
  81. if(ec == websocket::error::closed)
  82. break;
  83. if(ec)
  84. return fail(ec, "read");
  85. // Echo the message back
  86. ws.text(ws.got_text());
  87. ws.async_write(buffer.data(), yield[ec]);
  88. if(ec)
  89. return fail(ec, "write");
  90. }
  91. }
  92. //------------------------------------------------------------------------------
  93. // Accepts incoming connections and launches the sessions
  94. void
  95. do_listen(
  96. net::io_context& ioc,
  97. ssl::context& ctx,
  98. tcp::endpoint endpoint,
  99. net::yield_context yield)
  100. {
  101. beast::error_code ec;
  102. // Open the acceptor
  103. tcp::acceptor acceptor(ioc);
  104. acceptor.open(endpoint.protocol(), ec);
  105. if(ec)
  106. return fail(ec, "open");
  107. // Allow address reuse
  108. acceptor.set_option(net::socket_base::reuse_address(true), ec);
  109. if(ec)
  110. return fail(ec, "set_option");
  111. // Bind to the server address
  112. acceptor.bind(endpoint, ec);
  113. if(ec)
  114. return fail(ec, "bind");
  115. // Start listening for connections
  116. acceptor.listen(net::socket_base::max_listen_connections, ec);
  117. if(ec)
  118. return fail(ec, "listen");
  119. for(;;)
  120. {
  121. tcp::socket socket(ioc);
  122. acceptor.async_accept(socket, yield[ec]);
  123. if(ec)
  124. fail(ec, "accept");
  125. else
  126. boost::asio::spawn(
  127. acceptor.get_executor(),
  128. std::bind(
  129. &do_session,
  130. websocket::stream<beast::ssl_stream<
  131. beast::tcp_stream>>(std::move(socket), ctx),
  132. std::placeholders::_1));
  133. }
  134. }
  135. int main(int argc, char* argv[])
  136. {
  137. // Check command line arguments.
  138. if (argc != 4)
  139. {
  140. std::cerr <<
  141. "Usage: websocket-server-coro-ssl <address> <port> <threads>\n" <<
  142. "Example:\n" <<
  143. " websocket-server-coro-ssl 0.0.0.0 8080 1\n";
  144. return EXIT_FAILURE;
  145. }
  146. auto const address = net::ip::make_address(argv[1]);
  147. auto const port = static_cast<unsigned short>(std::atoi(argv[2]));
  148. auto const threads = std::max<int>(1, std::atoi(argv[3]));
  149. // The io_context is required for all I/O
  150. net::io_context ioc{threads};
  151. // The SSL context is required, and holds certificates
  152. ssl::context ctx{ssl::context::tlsv12};
  153. // This holds the self-signed certificate used by the server
  154. load_server_certificate(ctx);
  155. // Spawn a listening port
  156. boost::asio::spawn(ioc,
  157. std::bind(
  158. &do_listen,
  159. std::ref(ioc),
  160. std::ref(ctx),
  161. tcp::endpoint{address, port},
  162. std::placeholders::_1));
  163. // Run the I/O service on the requested number of threads
  164. std::vector<std::thread> v;
  165. v.reserve(threads - 1);
  166. for(auto i = threads - 1; i > 0; --i)
  167. v.emplace_back(
  168. [&ioc]
  169. {
  170. ioc.run();
  171. });
  172. ioc.run();
  173. return EXIT_SUCCESS;
  174. }