2 // Copyright (c) 2016-2019 Vinnie Falco (vinnie dot falco at gmail dot com)
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)
7 // Official repository: https://github.com/boostorg/beast
10 //------------------------------------------------------------------------------
12 // Example: WebSocket server, stackless coroutine
14 //------------------------------------------------------------------------------
16 #include <boost/beast/core.hpp>
17 #include <boost/beast/websocket.hpp>
18 #include <boost/asio/coroutine.hpp>
19 #include <boost/asio/strand.hpp>
20 #include <boost/asio/dispatch.hpp>
30 namespace beast = boost::beast; // from <boost/beast.hpp>
31 namespace http = beast::http; // from <boost/beast/http.hpp>
32 namespace websocket = beast::websocket; // from <boost/beast/websocket.hpp>
33 namespace net = boost::asio; // from <boost/asio.hpp>
34 using tcp = boost::asio::ip::tcp; // from <boost/asio/ip/tcp.hpp>
36 //------------------------------------------------------------------------------
40 fail(beast::error_code ec, char const* what)
42 std::cerr << what << ": " << ec.message() << "\n";
45 // Echoes back all received WebSocket messages
47 : public boost::asio::coroutine
48 , public std::enable_shared_from_this<session>
50 websocket::stream<beast::tcp_stream> ws_;
51 beast::flat_buffer buffer_;
54 // Take ownership of the socket
56 session(tcp::socket socket)
57 : ws_(std::move(socket))
61 // Start the asynchronous operation
65 // We need to be executing within a strand to perform async operations
66 // on the I/O objects in this session. Although not strictly necessary
67 // for single-threaded contexts, this example code is written to be
68 // thread-safe by default.
69 net::dispatch(ws_.get_executor(),
70 beast::bind_front_handler(&session::loop,
76 #include <boost/asio/yield.hpp>
81 std::size_t bytes_transferred)
83 boost::ignore_unused(bytes_transferred);
86 // Set suggested timeout settings for the websocket
88 websocket::stream_base::timeout::suggested(
89 beast::role_type::server));
91 // Set a decorator to change the Server of the handshake
92 ws_.set_option(websocket::stream_base::decorator(
93 [](websocket::response_type& res)
95 res.set(http::field::server,
96 std::string(BOOST_BEAST_VERSION_STRING) +
97 " websocket-server-stackless");
100 // Accept the websocket handshake
101 yield ws_.async_accept(
105 std::placeholders::_1,
108 return fail(ec, "accept");
112 // Read a message into our buffer
113 yield ws_.async_read(
118 std::placeholders::_1,
119 std::placeholders::_2));
120 if(ec == websocket::error::closed)
122 // This indicates that the session was closed
129 ws_.text(ws_.got_text());
130 yield ws_.async_write(
135 std::placeholders::_1,
136 std::placeholders::_2));
138 return fail(ec, "write");
141 buffer_.consume(buffer_.size());
146 #include <boost/asio/unyield.hpp>
149 //------------------------------------------------------------------------------
151 // Accepts incoming connections and launches the sessions
153 : public boost::asio::coroutine
154 , public std::enable_shared_from_this<listener>
156 net::io_context& ioc_;
157 tcp::acceptor acceptor_;
162 net::io_context& ioc,
163 tcp::endpoint endpoint)
165 , acceptor_(net::make_strand(ioc))
166 , socket_(net::make_strand(ioc))
168 beast::error_code ec;
171 acceptor_.open(endpoint.protocol(), ec);
178 // Allow address reuse
179 acceptor_.set_option(net::socket_base::reuse_address(true), ec);
182 fail(ec, "set_option");
186 // Bind to the server address
187 acceptor_.bind(endpoint, ec);
194 // Start listening for connections
196 net::socket_base::max_listen_connections, ec);
204 // Start accepting incoming connections
213 #include <boost/asio/yield.hpp>
216 loop(beast::error_code ec = {})
222 yield acceptor_.async_accept(
227 std::placeholders::_1));
234 // Create the session and run it
235 std::make_shared<session>(std::move(socket_))->run();
238 // Make sure each session gets its own strand
239 socket_ = tcp::socket(net::make_strand(ioc_));
244 #include <boost/asio/unyield.hpp>
247 //------------------------------------------------------------------------------
249 int main(int argc, char* argv[])
251 // Check command line arguments.
255 "Usage: websocket-server-stackless <address> <port> <threads>\n" <<
257 " websocket-server-stackless 0.0.0.0 8080 1\n";
260 auto const address = net::ip::make_address(argv[1]);
261 auto const port = static_cast<unsigned short>(std::atoi(argv[2]));
262 auto const threads = std::max<int>(1, std::atoi(argv[3]));
264 // The io_context is required for all I/O
265 net::io_context ioc{threads};
267 // Create and launch a listening port
268 std::make_shared<listener>(ioc, tcp::endpoint{address, port})->run();
270 // Run the I/O service on the requested number of threads
271 std::vector<std::thread> v;
272 v.reserve(threads - 1);
273 for(auto i = threads - 1; i > 0; --i)