Created
July 24, 2023 07:52
-
-
Save M0nteCarl0/71559f891a888d0cfdf016c0a5b3c10f to your computer and use it in GitHub Desktop.
Boost.asio multi thread TCP server
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <boost/asio.hpp> | |
#include <boost/thread.hpp> | |
using boost::asio::ip::tcp; | |
void session(tcp::socket socket) | |
{ | |
try | |
{ | |
boost::asio::streambuf buffer; | |
boost::system::error_code error; | |
while (boost::asio::read(socket, buffer, error)) | |
{ | |
std::string message(boost::asio::buffers_begin(buffer.data()), | |
boost::asio::buffers_end(buffer.data())); | |
buffer.consume(buffer.size()); | |
// Process the received message | |
std::cout << "Received message: " << message << std::endl; | |
// Send a response | |
std::string response = "Server response"; | |
boost::asio::write(socket, boost::asio::buffer(response), error); | |
} | |
if (error != boost::asio::error::eof) | |
{ | |
throw boost::system::system_error(error); | |
} | |
} | |
catch (std::exception& e) | |
{ | |
std::cerr << "Exception in session: " << e.what() << std::endl; | |
} | |
} | |
int main() | |
{ | |
try | |
{ | |
boost::asio::io_context io_context; | |
// Create an acceptor to listen on the specified port | |
tcp::acceptor acceptor(io_context, tcp::endpoint(tcp::v4(), 12345)); | |
while (true) | |
{ | |
// Create a socket and initiate an asynchronous accept operation | |
tcp::socket socket(io_context); | |
acceptor.accept(socket); | |
// Start a new thread to handle the session | |
boost::thread thread(boost::bind(session, std::move(socket))); | |
thread.detach(); | |
} | |
} | |
catch (std::exception& e) | |
{ | |
std::cerr << "Exception in server: " << e.what() << std::endl; | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment