I'm creating a server using boost::asio::ip::tcp, but I'm having problems using streams to do this.
The design pattern I'm using is:
- Server initializes a boost::asio::ip::tcp::acceptor, and a boost::asio::ip::tcp::iostream.
- Server listens to port with a boost::asio::ip::tcp::acceptor, using async_accept, accepting to the
streamobject. - When an incomming connection occurs, a new
Sessionobject is created. The stream object is passed to theSession, then we repeat step 2 with a new iostream object.
The code looks like this:
class Session; // Ctor: Session(asio::ip::tcp::stream tcp_stream)
class Server
{
public:
Server(boost::asio::io_service& p_service, unsigned p_port) :
m_service(p_service),
m_acc(m_service, boost::asio::ip::tcp::endpoint( asio::ip::tcp::v4(), p_port ) )
{
m_acc.async_accept(
*m_tcp_stream.rdbuf(),
std::bind(&Server::AcceptHandler, this, _1)
);
}
private:
void AcceptHandler(const boost::system::error_code& p_error)
{
if( !p_error )
{
boost::asio::ip::tcp::iostream tcp_stream;
std::swap(m_tcp_stream, tcp_stream);
new Session( std::move(tcp_stream) );
m_acc.async_accept(
*m_tcp_stream.rdbuf(),
std::bind(&Server::AcceptHandler, this, _1)
);
}
}
private:
boost::asio::io_service& m_service;
boost::asio::ip::tcp::iostream m_tcp_stream;
boost::asio::ip::tcp::acceptor m_acc;
};
My problem is that boost::asio::ip::tcp::iostream has no move ctor. This prevents the std::swap() or new Session() lines from compiling.
I could use this pattern with boost::asio::ip::tcp::socket because it supports the move ctor, but for some reason, streams don't support it. If I could extract a stream from a socket, then I'd be able to work around this, but I can't figure out how to do that.
What's the best way to accept TCP streams and pass the connections to objects which handle sessions?