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 SSL server, stackless coroutine
14 //------------------------------------------------------------------------------
16 #include "example/common/server_certificate.hpp"
18 #include <boost/beast/core.hpp>
19 #include <boost/beast/ssl.hpp>
20 #include <boost/beast/websocket.hpp>
21 #include <boost/beast/websocket/ssl.hpp>
22 #include <boost/asio/coroutine.hpp>
23 #include <boost/asio/strand.hpp>
24 #include <boost/asio/dispatch.hpp>
34 namespace beast = boost::beast; // from <boost/beast.hpp>
35 namespace http = beast::http; // from <boost/beast/http.hpp>
36 namespace websocket = beast::websocket; // from <boost/beast/websocket.hpp>
37 namespace net = boost::asio; // from <boost/asio.hpp>
38 namespace ssl = boost::asio::ssl; // from <boost/asio/ssl.hpp>
39 using tcp = boost::asio::ip::tcp; // from <boost/asio/ip/tcp.hpp>
41 //------------------------------------------------------------------------------
45 fail(beast::error_code ec, char const* what)
47 std::cerr << what << ": " << ec.message() << "\n";
50 // Echoes back all received WebSocket messages
52 : public boost::asio::coroutine
53 , public std::enable_shared_from_this<session>
55 websocket::stream<beast::ssl_stream<beast::tcp_stream>> ws_;
56 beast::flat_buffer buffer_;
59 // Take ownership of the socket
60 session(tcp::socket&& socket, ssl::context& ctx)
61 : ws_(std::move(socket), ctx)
65 // Start the asynchronous operation
69 // We need to be executing within a strand to perform async operations
70 // on the I/O objects in this session. Although not strictly necessary
71 // for single-threaded contexts, this example code is written to be
72 // thread-safe by default.
73 net::dispatch(ws_.get_executor(),
74 beast::bind_front_handler(&session::loop,
80 #include <boost/asio/yield.hpp>
85 std::size_t bytes_transferred)
87 boost::ignore_unused(bytes_transferred);
92 beast::get_lowest_layer(ws_).expires_after(std::chrono::seconds(30));
94 // Perform the SSL handshake
95 yield ws_.next_layer().async_handshake(
96 ssl::stream_base::server,
100 std::placeholders::_1,
103 return fail(ec, "handshake");
105 // Turn off the timeout on the tcp_stream, because
106 // the websocket stream has its own timeout system.
107 beast::get_lowest_layer(ws_).expires_never();
109 // Set suggested timeout settings for the websocket
111 websocket::stream_base::timeout::suggested(
112 beast::role_type::server));
114 // Set a decorator to change the Server of the handshake
115 ws_.set_option(websocket::stream_base::decorator(
116 [](websocket::response_type& res)
118 res.set(http::field::server,
119 std::string(BOOST_BEAST_VERSION_STRING) +
120 " websocket-server-stackless-ssl");
123 // Accept the websocket handshake
124 yield ws_.async_accept(
128 std::placeholders::_1,
131 return fail(ec, "accept");
135 // Read a message into our buffer
136 yield ws_.async_read(
141 std::placeholders::_1,
142 std::placeholders::_2));
143 if(ec == websocket::error::closed)
145 // This indicates that the session was closed
152 ws_.text(ws_.got_text());
153 yield ws_.async_write(
158 std::placeholders::_1,
159 std::placeholders::_2));
161 return fail(ec, "write");
164 buffer_.consume(buffer_.size());
169 #include <boost/asio/unyield.hpp>
172 //------------------------------------------------------------------------------
174 // Accepts incoming connections and launches the sessions
176 : public boost::asio::coroutine
177 , public std::enable_shared_from_this<listener>
179 net::io_context& ioc_;
181 tcp::acceptor acceptor_;
186 net::io_context& ioc,
188 tcp::endpoint endpoint)
194 beast::error_code ec;
197 acceptor_.open(endpoint.protocol(), ec);
204 // Allow address reuse
205 acceptor_.set_option(net::socket_base::reuse_address(true), ec);
208 fail(ec, "set_option");
212 // Bind to the server address
213 acceptor_.bind(endpoint, ec);
220 // Start listening for connections
222 net::socket_base::max_listen_connections, ec);
230 // Start accepting incoming connections
239 #include <boost/asio/yield.hpp>
242 loop(beast::error_code ec = {})
248 yield acceptor_.async_accept(
253 std::placeholders::_1));
260 // Create the session and run it
261 std::make_shared<session>(std::move(socket_), ctx_)->run();
264 // Make sure each session gets its own strand
265 socket_ = tcp::socket(net::make_strand(ioc_));
270 #include <boost/asio/unyield.hpp>
273 //------------------------------------------------------------------------------
275 int main(int argc, char* argv[])
277 // Check command line arguments.
281 "Usage: websocket-server-async-ssl <address> <port> <threads>\n" <<
283 " websocket-server-async-ssl 0.0.0.0 8080 1\n";
286 auto const address = net::ip::make_address(argv[1]);
287 auto const port = static_cast<unsigned short>(std::atoi(argv[2]));
288 auto const threads = std::max<int>(1, std::atoi(argv[3]));
290 // The io_context is required for all I/O
291 net::io_context ioc{threads};
293 // The SSL context is required, and holds certificates
294 ssl::context ctx{ssl::context::tlsv12};
296 // This holds the self-signed certificate used by the server
297 load_server_certificate(ctx);
299 // Create and launch a listening port
300 std::make_shared<listener>(ioc, ctx, tcp::endpoint{address, port})->run();
302 // Run the I/O service on the requested number of threads
303 std::vector<std::thread> v;
304 v.reserve(threads - 1);
305 for(auto i = threads - 1; i > 0; --i)