Files
boost_beast/test/websocket/websocket_async_echo_server.hpp
T

410 lines
11 KiB
C++
Raw Normal View History

2016-05-07 17:06:46 -04:00
//
2017-02-06 20:07:03 -05:00
// Copyright (c) 2013-2017 Vinnie Falco (vinnie dot falco at gmail dot com)
2016-05-07 17:06:46 -04:00
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
2017-07-20 08:01:46 -07:00
2017-01-30 09:53:10 -05:00
#ifndef BEAST_WEBSOCKET_ASYNC_ECHO_SERVER_HPP
#define BEAST_WEBSOCKET_ASYNC_ECHO_SERVER_HPP
2017-07-20 08:01:46 -07:00
#include <beast/core/multi_buffer.hpp>
2017-01-30 09:53:10 -05:00
#include <beast/websocket/stream.hpp>
#include <boost/lexical_cast.hpp>
2017-07-20 08:01:46 -07:00
#include <boost/optional.hpp>
2017-01-30 09:53:10 -05:00
#include <atomic>
2017-07-20 08:01:46 -07:00
#include <functional>
#include <memory>
2017-01-30 09:53:10 -05:00
#include <mutex>
2016-11-02 17:34:53 -04:00
#include <ostream>
2017-01-30 09:53:10 -05:00
#include <string>
#include <thread>
#include <type_traits>
#include <typeindex>
#include <unordered_map>
#include <utility>
2016-11-02 17:34:53 -04:00
2017-07-20 08:01:46 -07:00
namespace websocket {
2017-01-30 09:53:10 -05:00
/** Asynchronous WebSocket echo client/server
*/
2016-08-26 09:11:06 -04:00
class async_echo_server
2017-07-20 08:01:46 -07:00
{
public:
2017-01-30 09:53:10 -05:00
using error_code = beast::error_code;
2017-07-20 08:01:46 -07:00
using address_type = boost::asio::ip::address;
using socket_type = boost::asio::ip::tcp::socket;
2017-01-30 09:53:10 -05:00
using endpoint_type = boost::asio::ip::tcp::endpoint;
2017-07-20 08:01:46 -07:00
private:
2017-01-30 09:53:10 -05:00
/** A container of type-erased option setters.
*/
template<class NextLayer>
class options_set
{
// workaround for std::function bug in msvc
struct callable
{
virtual ~callable() = default;
virtual void operator()(
beast::websocket::stream<NextLayer>&) = 0;
};
template<class T>
class callable_impl : public callable
{
T t_;
public:
template<class U>
callable_impl(U&& u)
: t_(std::forward<U>(u))
{
}
void
operator()(beast::websocket::stream<NextLayer>& ws)
{
t_(ws);
}
};
template<class Opt>
class lambda
{
Opt opt_;
public:
lambda(lambda&&) = default;
lambda(lambda const&) = default;
lambda(Opt const& opt)
: opt_(opt)
{
}
void
operator()(beast::websocket::stream<NextLayer>& ws) const
{
ws.set_option(opt_);
}
};
std::unordered_map<std::type_index,
std::unique_ptr<callable>> list_;
public:
template<class Opt>
void
set_option(Opt const& opt)
{
std::unique_ptr<callable> p;
p.reset(new callable_impl<lambda<Opt>>{opt});
list_[std::type_index{
typeid(Opt)}] = std::move(p);
}
void
set_options(beast::websocket::stream<NextLayer>& ws)
{
for(auto const& op : list_)
(*op.second)(ws);
}
};
2016-11-02 17:34:53 -04:00
std::ostream* log_;
2017-07-20 08:01:46 -07:00
boost::asio::io_service ios_;
socket_type sock_;
2017-01-30 09:53:10 -05:00
endpoint_type ep_;
2017-07-20 08:01:46 -07:00
boost::asio::ip::tcp::acceptor acceptor_;
std::vector<std::thread> thread_;
2016-11-02 17:34:53 -04:00
boost::optional<boost::asio::io_service::work> work_;
2016-10-24 18:41:25 -04:00
options_set<socket_type> opts_;
2017-07-20 08:01:46 -07:00
public:
2016-11-18 13:48:11 -05:00
async_echo_server(async_echo_server const&) = delete;
async_echo_server& operator=(async_echo_server const&) = delete;
2017-01-30 09:53:10 -05:00
/** Constructor.
@param log A pointer to a stream to log to, or `nullptr`
to disable logging.
@param threads The number of threads in the io_service.
*/
2016-11-02 17:34:53 -04:00
async_echo_server(std::ostream* log,
std::size_t threads)
: log_(log)
, sock_(ios_)
2017-07-20 08:01:46 -07:00
, acceptor_(ios_)
2016-11-02 17:34:53 -04:00
, work_(ios_)
2017-07-20 08:01:46 -07:00
{
thread_.reserve(threads);
for(std::size_t i = 0; i < threads; ++i)
thread_.emplace_back(
[&]{ ios_.run(); });
}
2017-01-30 09:53:10 -05:00
/** Destructor.
*/
2016-08-26 09:11:06 -04:00
~async_echo_server()
2017-07-20 08:01:46 -07:00
{
2016-11-02 17:34:53 -04:00
work_ = boost::none;
2017-07-20 08:01:46 -07:00
error_code ec;
ios_.dispatch(
[&]{ acceptor_.close(ec); });
for(auto& t : thread_)
t.join();
}
2017-01-30 09:53:10 -05:00
/** Return the listening endpoint.
*/
endpoint_type
local_endpoint() const
{
return acceptor_.local_endpoint();
}
/** Set a websocket option.
The option will be applied to all new connections.
@param opt The option to apply.
*/
2016-10-24 18:41:25 -04:00
template<class Opt>
2016-11-02 17:34:53 -04:00
void
2016-10-24 18:41:25 -04:00
set_option(Opt const& opt)
2016-11-02 17:34:53 -04:00
{
2016-10-24 18:41:25 -04:00
opts_.set_option(opt);
}
2017-01-30 09:53:10 -05:00
/** Open a listening port.
@param ep The address and port to bind to.
@param ec Set to the error, if any occurred.
*/
2016-10-24 18:41:25 -04:00
void
open(endpoint_type const& ep, error_code& ec)
{
acceptor_.open(ep.protocol(), ec);
if(ec)
2017-01-30 09:53:10 -05:00
return fail("open", ec);
2016-10-24 18:41:25 -04:00
acceptor_.set_option(
boost::asio::socket_base::reuse_address{true});
acceptor_.bind(ep, ec);
if(ec)
2017-01-30 09:53:10 -05:00
return fail("bind", ec);
2016-10-24 18:41:25 -04:00
acceptor_.listen(
boost::asio::socket_base::max_connections, ec);
if(ec)
2017-01-30 09:53:10 -05:00
return fail("listen", ec);
acceptor_.async_accept(sock_, ep_,
2016-10-24 18:41:25 -04:00
std::bind(&async_echo_server::on_accept, this,
2017-05-10 13:08:11 -07:00
std::placeholders::_1));
2016-11-02 17:34:53 -04:00
}
2017-07-20 08:01:46 -07:00
private:
2017-01-30 09:53:10 -05:00
class peer
2017-07-20 08:01:46 -07:00
{
struct data
{
2016-11-02 17:34:53 -04:00
async_echo_server& server;
2017-01-30 09:53:10 -05:00
endpoint_type ep;
2017-07-20 08:01:46 -07:00
int state = 0;
2017-01-30 09:53:10 -05:00
beast::websocket::stream<socket_type> ws;
2016-05-15 16:22:25 -04:00
boost::asio::io_service::strand strand;
beast::multi_buffer db;
2017-01-30 09:53:10 -05:00
std::size_t id;
2017-07-20 08:01:46 -07:00
2016-11-02 17:34:53 -04:00
data(async_echo_server& server_,
2017-01-30 09:53:10 -05:00
endpoint_type const& ep_,
2016-11-02 17:34:53 -04:00
socket_type&& sock_)
: server(server_)
2017-01-30 09:53:10 -05:00
, ep(ep_)
, ws(std::move(sock_))
2016-05-15 16:22:25 -04:00
, strand(ws.get_io_service())
2017-07-20 08:01:46 -07:00
, id([]
{
2017-01-30 09:53:10 -05:00
static std::atomic<std::size_t> n{0};
2017-07-20 08:01:46 -07:00
return ++n;
}())
{
}
};
2017-01-30 09:53:10 -05:00
// VFALCO This could be unique_ptr in [Net.TS]
2017-07-20 08:01:46 -07:00
std::shared_ptr<data> d_;
public:
2017-01-30 09:53:10 -05:00
peer(peer&&) = default;
peer(peer const&) = default;
peer& operator=(peer&&) = delete;
peer& operator=(peer const&) = delete;
2017-07-20 08:01:46 -07:00
template<class... Args>
explicit
2017-01-30 09:53:10 -05:00
peer(async_echo_server& server,
endpoint_type const& ep, socket_type&& sock,
Args&&... args)
: d_(std::make_shared<data>(server, ep,
2017-07-20 08:01:46 -07:00
std::forward<socket_type>(sock),
std::forward<Args>(args)...))
{
auto& d = *d_;
2016-10-24 18:41:25 -04:00
d.server.opts_.set_options(d.ws);
2017-07-20 08:01:46 -07:00
run();
}
void run()
{
auto& d = *d_;
2017-04-25 09:35:22 -07:00
d.ws.async_accept_ex(
[](beast::websocket::response_type& res)
{
2017-06-05 19:28:17 -07:00
res.insert(
2017-04-25 09:35:22 -07:00
"Server", "async_echo_server");
},
std::move(*this));
2017-07-20 08:01:46 -07:00
}
2016-08-26 09:06:55 -04:00
template<class DynamicBuffer, std::size_t N>
2016-05-15 16:22:25 -04:00
static
bool
2016-08-26 09:06:55 -04:00
match(DynamicBuffer& db, char const(&s)[N])
2016-05-15 16:22:25 -04:00
{
using boost::asio::buffer;
using boost::asio::buffer_copy;
2016-08-26 09:06:55 -04:00
if(db.size() < N-1)
2016-05-15 16:22:25 -04:00
return false;
2017-01-30 09:53:10 -05:00
beast::static_string<N-1> t;
2016-05-15 16:22:25 -04:00
t.resize(N-1);
buffer_copy(buffer(t.data(), t.size()),
2016-08-26 09:06:55 -04:00
db.data());
2016-05-15 16:22:25 -04:00
if(t != s)
return false;
2016-08-26 09:06:55 -04:00
db.consume(N-1);
2016-05-15 16:22:25 -04:00
return true;
}
void operator()(error_code ec, std::size_t)
{
(*this)(ec);
}
2017-07-20 08:01:46 -07:00
void operator()(error_code ec)
{
2016-05-15 16:22:25 -04:00
using boost::asio::buffer;
using boost::asio::buffer_copy;
2017-07-20 08:01:46 -07:00
auto& d = *d_;
switch(d.state)
2017-07-20 08:01:46 -07:00
{
// did accept
case 0:
if(ec)
2017-01-30 09:53:10 -05:00
return fail("async_accept", ec);
2017-07-20 08:01:46 -07:00
// start
case 1:
if(ec)
2017-01-30 09:53:10 -05:00
return fail("async_handshake", ec);
2016-08-26 09:06:55 -04:00
d.db.consume(d.db.size());
2017-07-20 08:01:46 -07:00
// read message
d.state = 2;
d.ws.async_read(d.db,
2016-05-15 16:22:25 -04:00
d.strand.wrap(std::move(*this)));
2017-07-20 08:01:46 -07:00
return;
// got message
case 2:
2017-01-30 09:53:10 -05:00
if(ec == beast::websocket::error::closed)
2017-07-20 08:01:46 -07:00
return;
if(ec)
2017-01-30 09:53:10 -05:00
return fail("async_read", ec);
2016-08-26 09:06:55 -04:00
if(match(d.db, "RAW"))
2016-05-15 16:22:25 -04:00
{
d.state = 1;
boost::asio::async_write(d.ws.next_layer(),
2016-08-26 09:06:55 -04:00
d.db.data(), d.strand.wrap(std::move(*this)));
2016-05-15 16:22:25 -04:00
return;
}
2016-08-26 09:06:55 -04:00
else if(match(d.db, "TEXT"))
2016-05-15 16:22:25 -04:00
{
d.state = 1;
d.ws.binary(false);
2016-05-15 16:22:25 -04:00
d.ws.async_write(
2016-08-26 09:06:55 -04:00
d.db.data(), d.strand.wrap(std::move(*this)));
2016-05-15 16:22:25 -04:00
return;
}
2016-08-26 09:06:55 -04:00
else if(match(d.db, "PING"))
2016-05-15 16:22:25 -04:00
{
2017-01-30 09:53:10 -05:00
beast::websocket::ping_data payload;
2016-08-26 09:06:55 -04:00
d.db.consume(buffer_copy(
2016-05-15 16:22:25 -04:00
buffer(payload.data(), payload.size()),
2016-08-26 09:06:55 -04:00
d.db.data()));
2016-05-15 16:22:25 -04:00
d.state = 1;
d.ws.async_ping(payload,
d.strand.wrap(std::move(*this)));
return;
}
2016-08-26 09:06:55 -04:00
else if(match(d.db, "CLOSE"))
2016-05-15 16:22:25 -04:00
{
d.state = 1;
d.ws.async_close({},
d.strand.wrap(std::move(*this)));
return;
}
2017-07-20 08:01:46 -07:00
// write message
d.state = 1;
d.ws.binary(d.ws.got_binary());
2016-08-26 09:06:55 -04:00
d.ws.async_write(d.db.data(),
2016-05-15 16:22:25 -04:00
d.strand.wrap(std::move(*this)));
2017-07-20 08:01:46 -07:00
return;
}
}
private:
void
2017-01-30 09:53:10 -05:00
fail(std::string what, error_code ec)
2017-07-20 08:01:46 -07:00
{
auto& d = *d_;
2016-11-02 17:34:53 -04:00
if(d.server.log_)
2017-01-30 09:53:10 -05:00
if(ec != beast::websocket::error::closed)
d.server.fail("[#" + std::to_string(d.id) +
" " + boost::lexical_cast<std::string>(d.ep) +
"] " + what, ec);
2017-07-20 08:01:46 -07:00
}
};
void
2017-01-30 09:53:10 -05:00
fail(std::string what, error_code ec)
2017-07-20 08:01:46 -07:00
{
if(log_)
2017-01-30 09:53:10 -05:00
{
static std::mutex m;
std::lock_guard<std::mutex> lock{m};
2016-11-02 17:34:53 -04:00
(*log_) << what << ": " <<
ec.message() << std::endl;
2017-07-20 08:01:46 -07:00
}
}
void
on_accept(error_code ec)
{
if(! acceptor_.is_open())
return;
2016-05-15 16:22:25 -04:00
if(ec == boost::asio::error::operation_aborted)
return;
2017-01-30 09:53:10 -05:00
if(ec)
fail("accept", ec);
peer{*this, ep_, std::move(sock_)};
acceptor_.async_accept(sock_, ep_,
2016-08-26 09:11:06 -04:00
std::bind(&async_echo_server::on_accept, this,
2017-05-10 13:08:11 -07:00
std::placeholders::_1));
2017-07-20 08:01:46 -07:00
}
};
} // websocket
#endif