I am trying to create a tcp synchronous server. My main thread would create a port listen, and the incoming connection was handled by the thread.
My code is:
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 (ie 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 works with more than one client connecting to the server; however, it also works if I delete the thread pool. Can someone explain to me why this is so? Do I need a thread pool?
source share