|
| 1 | +/* |
| 2 | +This seemed a sufficiently common pattern so as to be worth abstracting. |
| 3 | +
|
| 4 | +*/ |
| 5 | + |
| 6 | +#ifndef ASIO_SERVER_H |
| 7 | +#define ASIO_SERVER_H |
| 8 | + |
| 9 | +#include <functional> |
| 10 | +#include <memory> |
| 11 | +#include <boost/asio.hpp> |
| 12 | + |
| 13 | + |
| 14 | +// Convenience class for handlers. |
| 15 | +// To use, define a class Foo which inherits from asio_handler<Foo>, calls its |
| 16 | +// constructor, and overwrites 'handle'. |
| 17 | +// eg: |
| 18 | +/* |
| 19 | +class handler: public asio_handler<handler> { |
| 20 | + public: |
| 21 | + handler(boost::asio::io_service& io_service) : asio_handler(io_service) {} |
| 22 | + void handle() { |
| 23 | + // do something like read from socket_ |
| 24 | + } |
| 25 | +} |
| 26 | +
|
| 27 | +*/ |
| 28 | +template<typename T> |
| 29 | +class asio_handler : public std::enable_shared_from_this<T> { |
| 30 | + public: |
| 31 | + asio_handler(boost::asio::io_service& io_service) |
| 32 | + : socket_(io_service) {} |
| 33 | + |
| 34 | + boost::asio::local::stream_protocol::socket& socket() { |
| 35 | + return socket_; |
| 36 | + } |
| 37 | + |
| 38 | + void handle() { |
| 39 | + |
| 40 | + } |
| 41 | + |
| 42 | + protected: |
| 43 | + boost::asio::local::stream_protocol::socket socket_; |
| 44 | +}; |
| 45 | + |
| 46 | + |
| 47 | +// HANDLER must have a constructor with a 'boost::asio::io_service&' as its sole parameter, |
| 48 | +// must implement a 'handle' fn taking no parameters. |
| 49 | +// and must implement a 'socket' fn taking no parameters and returning a 'boost::asio::local::stream_protocol::socket' |
| 50 | +// this being the socket it wants to talk on. |
| 51 | +// In practice, just derive from asio_handler. |
| 52 | +template<typename HANDLER> |
| 53 | +class asio_server { |
| 54 | +public: |
| 55 | + boost::asio::io_service& io_service_; |
| 56 | + boost::asio::local::stream_protocol::acceptor acceptor_; |
| 57 | + |
| 58 | + asio_server(boost::asio::io_service& io_service, boost::asio::local::stream_protocol::endpoint endpoint) |
| 59 | + : io_service_(io_service), acceptor_(io_service, endpoint) { |
| 60 | + auto the_session = std::make_shared<HANDLER>(io_service_); |
| 61 | + acceptor_.async_accept(the_session->socket(), std::bind(&asio_server::handle_accept, this, the_session, std::placeholders::_1)); |
| 62 | + } |
| 63 | + |
| 64 | + void handle_accept(std::shared_ptr<HANDLER> session, const boost::system::error_code& error) { |
| 65 | + if(!error) |
| 66 | + session->handle(); |
| 67 | + |
| 68 | + session.reset(new HANDLER(io_service_)); |
| 69 | + acceptor_.async_accept(session->socket(), std::bind(&asio_server::handle_accept, this, session, std::placeholders::_1)); |
| 70 | + } |
| 71 | +}; |
| 72 | + |
| 73 | + |
| 74 | +#endif |
0 commit comments