websocket_server_fast.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480
  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, fast
  12. //
  13. //------------------------------------------------------------------------------
  14. /* This server contains the following ports:
  15. Synchronous <base port + 0>
  16. Asynchronous <base port + 1>
  17. Coroutine <base port + 2>
  18. This program is optimized for the Autobahn|Testsuite
  19. benchmarking and WebSocket compliants testing program.
  20. See:
  21. https://github.com/crossbario/autobahn-testsuite
  22. */
  23. #include <boost/beast/core.hpp>
  24. #include <boost/beast/http.hpp>
  25. #include <boost/beast/version.hpp>
  26. #include <boost/beast/websocket.hpp>
  27. #include <boost/asio/spawn.hpp>
  28. #include <boost/asio/strand.hpp>
  29. #include <algorithm>
  30. #include <cstdlib>
  31. #include <functional>
  32. #include <iostream>
  33. #include <memory>
  34. #include <string>
  35. #include <thread>
  36. #include <vector>
  37. namespace beast = boost::beast; // from <boost/beast.hpp>
  38. namespace http = beast::http; // from <boost/beast/http.hpp>
  39. namespace websocket = beast::websocket; // from <boost/beast/websocket.hpp>
  40. namespace net = boost::asio; // from <boost/asio.hpp>
  41. using tcp = boost::asio::ip::tcp; // from <boost/asio/ip/tcp.hpp>
  42. //------------------------------------------------------------------------------
  43. // Report a failure
  44. void
  45. fail(beast::error_code ec, char const* what)
  46. {
  47. std::cerr << (std::string(what) + ": " + ec.message() + "\n");
  48. }
  49. // Adjust settings on the stream
  50. template<class NextLayer>
  51. void
  52. setup_stream(websocket::stream<NextLayer>& ws)
  53. {
  54. // These values are tuned for Autobahn|Testsuite, and
  55. // should also be generally helpful for increased performance.
  56. websocket::permessage_deflate pmd;
  57. pmd.client_enable = true;
  58. pmd.server_enable = true;
  59. pmd.compLevel = 3;
  60. ws.set_option(pmd);
  61. ws.auto_fragment(false);
  62. // Autobahn|Testsuite needs this
  63. ws.read_message_max(64 * 1024 * 1024);
  64. }
  65. //------------------------------------------------------------------------------
  66. void
  67. do_sync_session(websocket::stream<beast::tcp_stream>& ws)
  68. {
  69. beast::error_code ec;
  70. setup_stream(ws);
  71. // Set a decorator to change the Server of the handshake
  72. ws.set_option(websocket::stream_base::decorator(
  73. [](websocket::response_type& res)
  74. {
  75. res.set(http::field::server, std::string(
  76. BOOST_BEAST_VERSION_STRING) + "-Sync");
  77. }));
  78. ws.accept(ec);
  79. if(ec)
  80. return fail(ec, "accept");
  81. for(;;)
  82. {
  83. beast::flat_buffer buffer;
  84. ws.read(buffer, ec);
  85. if(ec == websocket::error::closed)
  86. break;
  87. if(ec)
  88. return fail(ec, "read");
  89. ws.text(ws.got_text());
  90. ws.write(buffer.data(), ec);
  91. if(ec)
  92. return fail(ec, "write");
  93. }
  94. }
  95. void
  96. do_sync_listen(
  97. net::io_context& ioc,
  98. tcp::endpoint endpoint)
  99. {
  100. beast::error_code ec;
  101. tcp::acceptor acceptor{ioc, endpoint};
  102. for(;;)
  103. {
  104. tcp::socket socket{ioc};
  105. acceptor.accept(socket, ec);
  106. if(ec)
  107. return fail(ec, "accept");
  108. std::thread(std::bind(
  109. &do_sync_session,
  110. websocket::stream<beast::tcp_stream>(
  111. std::move(socket)))).detach();
  112. }
  113. }
  114. //------------------------------------------------------------------------------
  115. // Echoes back all received WebSocket messages
  116. class async_session : public std::enable_shared_from_this<async_session>
  117. {
  118. websocket::stream<beast::tcp_stream> ws_;
  119. beast::flat_buffer buffer_;
  120. public:
  121. // Take ownership of the socket
  122. explicit
  123. async_session(tcp::socket&& socket)
  124. : ws_(std::move(socket))
  125. {
  126. setup_stream(ws_);
  127. }
  128. // Start the asynchronous operation
  129. void
  130. run()
  131. {
  132. // Set suggested timeout settings for the websocket
  133. ws_.set_option(
  134. websocket::stream_base::timeout::suggested(
  135. beast::role_type::server));
  136. // Set a decorator to change the Server of the handshake
  137. ws_.set_option(websocket::stream_base::decorator(
  138. [](websocket::response_type& res)
  139. {
  140. res.set(http::field::server, std::string(
  141. BOOST_BEAST_VERSION_STRING) + "-Async");
  142. }));
  143. // Accept the websocket handshake
  144. ws_.async_accept(
  145. beast::bind_front_handler(
  146. &async_session::on_accept,
  147. shared_from_this()));
  148. }
  149. void
  150. on_accept(beast::error_code ec)
  151. {
  152. if(ec)
  153. return fail(ec, "accept");
  154. // Read a message
  155. do_read();
  156. }
  157. void
  158. do_read()
  159. {
  160. // Read a message into our buffer
  161. ws_.async_read(
  162. buffer_,
  163. beast::bind_front_handler(
  164. &async_session::on_read,
  165. shared_from_this()));
  166. }
  167. void
  168. on_read(
  169. beast::error_code ec,
  170. std::size_t bytes_transferred)
  171. {
  172. boost::ignore_unused(bytes_transferred);
  173. // This indicates that the async_session was closed
  174. if(ec == websocket::error::closed)
  175. return;
  176. if(ec)
  177. fail(ec, "read");
  178. // Echo the message
  179. ws_.text(ws_.got_text());
  180. ws_.async_write(
  181. buffer_.data(),
  182. beast::bind_front_handler(
  183. &async_session::on_write,
  184. shared_from_this()));
  185. }
  186. void
  187. on_write(
  188. beast::error_code ec,
  189. std::size_t bytes_transferred)
  190. {
  191. boost::ignore_unused(bytes_transferred);
  192. if(ec)
  193. return fail(ec, "write");
  194. // Clear the buffer
  195. buffer_.consume(buffer_.size());
  196. // Do another read
  197. do_read();
  198. }
  199. };
  200. // Accepts incoming connections and launches the sessions
  201. class async_listener : public std::enable_shared_from_this<async_listener>
  202. {
  203. net::io_context& ioc_;
  204. tcp::acceptor acceptor_;
  205. public:
  206. async_listener(
  207. net::io_context& ioc,
  208. tcp::endpoint endpoint)
  209. : ioc_(ioc)
  210. , acceptor_(net::make_strand(ioc))
  211. {
  212. beast::error_code ec;
  213. // Open the acceptor
  214. acceptor_.open(endpoint.protocol(), ec);
  215. if(ec)
  216. {
  217. fail(ec, "open");
  218. return;
  219. }
  220. // Allow address reuse
  221. acceptor_.set_option(net::socket_base::reuse_address(true), ec);
  222. if(ec)
  223. {
  224. fail(ec, "set_option");
  225. return;
  226. }
  227. // Bind to the server address
  228. acceptor_.bind(endpoint, ec);
  229. if(ec)
  230. {
  231. fail(ec, "bind");
  232. return;
  233. }
  234. // Start listening for connections
  235. acceptor_.listen(
  236. net::socket_base::max_listen_connections, ec);
  237. if(ec)
  238. {
  239. fail(ec, "listen");
  240. return;
  241. }
  242. }
  243. // Start accepting incoming connections
  244. void
  245. run()
  246. {
  247. do_accept();
  248. }
  249. private:
  250. void
  251. do_accept()
  252. {
  253. // The new connection gets its own strand
  254. acceptor_.async_accept(
  255. net::make_strand(ioc_),
  256. beast::bind_front_handler(
  257. &async_listener::on_accept,
  258. shared_from_this()));
  259. }
  260. void
  261. on_accept(beast::error_code ec, tcp::socket socket)
  262. {
  263. if(ec)
  264. {
  265. fail(ec, "accept");
  266. }
  267. else
  268. {
  269. // Create the async_session and run it
  270. std::make_shared<async_session>(std::move(socket))->run();
  271. }
  272. // Accept another connection
  273. do_accept();
  274. }
  275. };
  276. //------------------------------------------------------------------------------
  277. void
  278. do_coro_session(
  279. websocket::stream<beast::tcp_stream>& ws,
  280. net::yield_context yield)
  281. {
  282. beast::error_code ec;
  283. setup_stream(ws);
  284. // Set suggested timeout settings for the websocket
  285. ws.set_option(
  286. websocket::stream_base::timeout::suggested(
  287. beast::role_type::server));
  288. // Set a decorator to change the Server of the handshake
  289. ws.set_option(websocket::stream_base::decorator(
  290. [](websocket::response_type& res)
  291. {
  292. res.set(http::field::server, std::string(
  293. BOOST_BEAST_VERSION_STRING) + "-Fiber");
  294. }));
  295. ws.async_accept(yield[ec]);
  296. if(ec)
  297. return fail(ec, "accept");
  298. for(;;)
  299. {
  300. beast::flat_buffer buffer;
  301. ws.async_read(buffer, yield[ec]);
  302. if(ec == websocket::error::closed)
  303. break;
  304. if(ec)
  305. return fail(ec, "read");
  306. ws.text(ws.got_text());
  307. ws.async_write(buffer.data(), yield[ec]);
  308. if(ec)
  309. return fail(ec, "write");
  310. }
  311. }
  312. void
  313. do_coro_listen(
  314. net::io_context& ioc,
  315. tcp::endpoint endpoint,
  316. net::yield_context yield)
  317. {
  318. beast::error_code ec;
  319. tcp::acceptor acceptor(ioc);
  320. acceptor.open(endpoint.protocol(), ec);
  321. if(ec)
  322. return fail(ec, "open");
  323. acceptor.set_option(net::socket_base::reuse_address(true), ec);
  324. if(ec)
  325. return fail(ec, "set_option");
  326. acceptor.bind(endpoint, ec);
  327. if(ec)
  328. return fail(ec, "bind");
  329. acceptor.listen(net::socket_base::max_listen_connections, ec);
  330. if(ec)
  331. return fail(ec, "listen");
  332. for(;;)
  333. {
  334. tcp::socket socket(ioc);
  335. acceptor.async_accept(socket, yield[ec]);
  336. if(ec)
  337. {
  338. fail(ec, "accept");
  339. continue;
  340. }
  341. boost::asio::spawn(
  342. acceptor.get_executor(),
  343. std::bind(
  344. &do_coro_session,
  345. websocket::stream<
  346. beast::tcp_stream>(std::move(socket)),
  347. std::placeholders::_1));
  348. }
  349. }
  350. //------------------------------------------------------------------------------
  351. int main(int argc, char* argv[])
  352. {
  353. // Check command line arguments.
  354. if (argc != 4)
  355. {
  356. std::cerr <<
  357. "Usage: websocket-server-fast <address> <starting-port> <threads>\n" <<
  358. "Example:\n"
  359. " websocket-server-fast 0.0.0.0 8080 1\n"
  360. " Connect to:\n"
  361. " starting-port+0 for synchronous,\n"
  362. " starting-port+1 for asynchronous,\n"
  363. " starting-port+2 for coroutine.\n";
  364. return EXIT_FAILURE;
  365. }
  366. auto const address = net::ip::make_address(argv[1]);
  367. auto const port = static_cast<unsigned short>(std::atoi(argv[2]));
  368. auto const threads = std::max<int>(1, std::atoi(argv[3]));
  369. // The io_context is required for all I/O
  370. net::io_context ioc{threads};
  371. // Create sync port
  372. std::thread(beast::bind_front_handler(
  373. &do_sync_listen,
  374. std::ref(ioc),
  375. tcp::endpoint{
  376. address,
  377. static_cast<unsigned short>(port + 0u)}
  378. )).detach();
  379. // Create async port
  380. std::make_shared<async_listener>(
  381. ioc,
  382. tcp::endpoint{
  383. address,
  384. static_cast<unsigned short>(port + 1u)})->run();
  385. // Create coro port
  386. boost::asio::spawn(ioc,
  387. std::bind(
  388. &do_coro_listen,
  389. std::ref(ioc),
  390. tcp::endpoint{
  391. address,
  392. static_cast<unsigned short>(port + 2u)},
  393. std::placeholders::_1));
  394. // Run the I/O service on the requested number of threads
  395. std::vector<std::thread> v;
  396. v.reserve(threads - 1);
  397. for(auto i = threads - 1; i > 0; --i)
  398. v.emplace_back(
  399. [&ioc]
  400. {
  401. ioc.run();
  402. });
  403. ioc.run();
  404. return EXIT_SUCCESS;
  405. }