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, asynchronous
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/strand.hpp>
23 #include <boost/asio/dispatch.hpp>
33 namespace beast = boost::beast; // from <boost/beast.hpp>
34 namespace http = beast::http; // from <boost/beast/http.hpp>
35 namespace websocket = beast::websocket; // from <boost/beast/websocket.hpp>
36 namespace net = boost::asio; // from <boost/asio.hpp>
37 namespace ssl = boost::asio::ssl; // from <boost/asio/ssl.hpp>
38 using tcp = boost::asio::ip::tcp; // from <boost/asio/ip/tcp.hpp>
40 //------------------------------------------------------------------------------
44 fail(beast::error_code ec, char const* what)
46 std::cerr << what << ": " << ec.message() << "\n";
49 // Echoes back all received WebSocket messages
50 class session : public std::enable_shared_from_this<session>
53 beast::ssl_stream<beast::tcp_stream>> ws_;
54 beast::flat_buffer buffer_;
57 // Take ownership of the socket
58 session(tcp::socket&& socket, ssl::context& ctx)
59 : ws_(std::move(socket), ctx)
63 // Get on the correct executor
67 // We need to be executing within a strand to perform async operations
68 // on the I/O objects in this session. Although not strictly necessary
69 // for single-threaded contexts, this example code is written to be
70 // thread-safe by default.
71 net::dispatch(ws_.get_executor(),
72 beast::bind_front_handler(
77 // Start the asynchronous operation
82 beast::get_lowest_layer(ws_).expires_after(std::chrono::seconds(30));
84 // Perform the SSL handshake
85 ws_.next_layer().async_handshake(
86 ssl::stream_base::server,
87 beast::bind_front_handler(
88 &session::on_handshake,
93 on_handshake(beast::error_code ec)
96 return fail(ec, "handshake");
98 // Turn off the timeout on the tcp_stream, because
99 // the websocket stream has its own timeout system.
100 beast::get_lowest_layer(ws_).expires_never();
102 // Set suggested timeout settings for the websocket
104 websocket::stream_base::timeout::suggested(
105 beast::role_type::server));
107 // Set a decorator to change the Server of the handshake
108 ws_.set_option(websocket::stream_base::decorator(
109 [](websocket::response_type& res)
111 res.set(http::field::server,
112 std::string(BOOST_BEAST_VERSION_STRING) +
113 " websocket-server-async-ssl");
116 // Accept the websocket handshake
118 beast::bind_front_handler(
120 shared_from_this()));
124 on_accept(beast::error_code ec)
127 return fail(ec, "accept");
136 // Read a message into our buffer
139 beast::bind_front_handler(
141 shared_from_this()));
146 beast::error_code ec,
147 std::size_t bytes_transferred)
149 boost::ignore_unused(bytes_transferred);
151 // This indicates that the session was closed
152 if(ec == websocket::error::closed)
159 ws_.text(ws_.got_text());
162 beast::bind_front_handler(
164 shared_from_this()));
169 beast::error_code ec,
170 std::size_t bytes_transferred)
172 boost::ignore_unused(bytes_transferred);
175 return fail(ec, "write");
178 buffer_.consume(buffer_.size());
185 //------------------------------------------------------------------------------
187 // Accepts incoming connections and launches the sessions
188 class listener : public std::enable_shared_from_this<listener>
190 net::io_context& ioc_;
192 tcp::acceptor acceptor_;
196 net::io_context& ioc,
198 tcp::endpoint endpoint)
201 , acceptor_(net::make_strand(ioc))
203 beast::error_code ec;
206 acceptor_.open(endpoint.protocol(), ec);
213 // Allow address reuse
214 acceptor_.set_option(net::socket_base::reuse_address(true), ec);
217 fail(ec, "set_option");
221 // Bind to the server address
222 acceptor_.bind(endpoint, ec);
229 // Start listening for connections
231 net::socket_base::max_listen_connections, ec);
239 // Start accepting incoming connections
250 // The new connection gets its own strand
251 acceptor_.async_accept(
252 net::make_strand(ioc_),
253 beast::bind_front_handler(
254 &listener::on_accept,
255 shared_from_this()));
259 on_accept(beast::error_code ec, tcp::socket socket)
267 // Create the session and run it
268 std::make_shared<session>(std::move(socket), ctx_)->run();
271 // Accept another connection
276 //------------------------------------------------------------------------------
278 int main(int argc, char* argv[])
280 // Check command line arguments.
284 "Usage: websocket-server-async-ssl <address> <port> <threads>\n" <<
286 " websocket-server-async-ssl 0.0.0.0 8080 1\n";
289 auto const address = net::ip::make_address(argv[1]);
290 auto const port = static_cast<unsigned short>(std::atoi(argv[2]));
291 auto const threads = std::max<int>(1, std::atoi(argv[3]));
293 // The io_context is required for all I/O
294 net::io_context ioc{threads};
296 // The SSL context is required, and holds certificates
297 ssl::context ctx{ssl::context::tlsv12};
299 // This holds the self-signed certificate used by the server
300 load_server_certificate(ctx);
302 // Create and launch a listening port
303 std::make_shared<listener>(ioc, ctx, tcp::endpoint{address, port})->run();
305 // Run the I/O service on the requested number of threads
306 std::vector<std::thread> v;
307 v.reserve(threads - 1);
308 for(auto i = threads - 1; i > 0; --i)