I am trying to create a tcp synchronous server. My main thread would create listen to a port, and an incoming connection would be handled by a thread.
My code:
void WorkerThread(boost::shared_ptr< boost::asio::io_service > io_service)
{
io_service->run();
}
void Application::server()
{
boost::shared_ptr< boost::asio::io_service > io(
new boost::asio::io_service()
);
boost::shared_ptr< boost::asio::io_service::work > work(
new boost::asio::io_service::work(*io)
);
// Open the acceptor with the option to reuse the address (i.e. SO_REUSEADDR
boost::asio::ip::tcp::acceptor acceptor(*io);
boost::asio::ip::tcp::endpoint endpoint(boost::asio::ip::tcp::v4(), 2198);
acceptor.open(endpoint.protocol());
acceptor.set_option(boost::asio::ip::tcp::acceptor::reuse_address(true));
acceptor.bind(endpoint);
acceptor.listen();
// pool of threads
boost::thread_group worker_threads;
for(int x = 0; x < 5; ++x)
{
worker_threads.create_thread(boost::bind(&WorkerThread, io));
}
while(true)
{
boost::shared_ptr< boost::asio::ip::tcp::socket > socket(
new boost::asio::ip::tcp::socket( *io )
);
acceptor.accept(*socket);
processConnection(*socket);
socket->close();
}
io->stop();
worker_threads.join_all();
}
void Application::processConnection(boost::asio::ip::tcp::socket & socket)
{
boost::asio::streambuf request_buffer;
std::istream request_stream(&request_buffer);
// repsonse buffer
boost::asio::streambuf response_buffer;
std::ostream response_stream(&response_buffer);
boost::asio::read_until(socket, request_buffer, "</message>");
// process request_buffer into response_buffer
boost::asio::write(socket, response_buffer);
}
The following is working with more than one client connecting to the server; however, it also work if I remove the pool of thread. Can anyone explain me why that is? Do I even need a pool of threads?
You do not need a pool of threads given your sample code. There is no need to invoke
io_service::run()in your context, see the documentationYou haven’t added any handlers to the
io_serviceso there is no need to invokerun(). If you use asynchronous methods such asasync_accept(), then you will need torun()theio_service.