Boost Asio Multithreaded TCP Synchronous Server

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?

+6
source share
2 answers

however, it also works if I delete a thread pool. Can anyone explain to me why this is so? Do I need a thread pool?

You do not need a thread pool based on your sample code. There is no need to call io_service::run() in your context, see documentation

The run() function blocks until all jobs have finished and there are no more handlers, or until io_service has stopped.

You have not added handlers to io_service , so there is no need to call run() . If you use asynchronous methods like async_accept() , you need to run() io_service .

+6
source

you may find it easier to read the code if you have typed forced material

Example

 typedef boost::asio::ip::tcp::socket TSocket; 

This does not directly help, but it will help

+1
source

Source: https://habr.com/ru/post/901460/


All Articles