websocket_server_coro.cpp 4.9 KB

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