基于boost1.6,创建一个线程来处理客户端连接请求,举例说明
时间: 2024-03-14 08:44:50 浏览: 150
BOOST写的通信例程客户端
5星 · 资源好评率100%
好的,以下是基于boost1.6创建一个线程来处理客户端连接请求的示例代码:
```cpp
#include <boost/asio.hpp>
#include <boost/thread.hpp>
#include <iostream>
void handle_client(boost::asio::ip::tcp::socket socket)
{
std::cout << "New client connected!" << std::endl;
boost::system::error_code error;
boost::asio::streambuf buffer;
while (boost::asio::read(socket, buffer, error))
{
std::string message(boost::asio::buffers_begin(buffer.data()), boost::asio::buffers_end(buffer.data()));
std::cout << "Received message: " << message << std::endl;
boost::asio::write(socket, boost::asio::buffer("Server received your message!"));
buffer.consume(buffer.size()); // clear buffer
}
std::cout << "Client disconnected!" << std::endl;
}
void accept_clients(boost::asio::io_service& io_service, boost::asio::ip::tcp::acceptor& acceptor)
{
while (true)
{
boost::asio::ip::tcp::socket socket(io_service);
acceptor.accept(socket);
boost::thread t(boost::bind(handle_client, std::move(socket)));
t.detach(); // detach thread to run independently
}
}
int main()
{
boost::asio::io_service io_service;
boost::asio::ip::tcp::acceptor acceptor(io_service, boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), 12345));
accept_clients(io_service, acceptor);
return 0;
}
```
这段代码会在端口号为12345的地址上监听客户端连接请求,当有客户端连接时,会创建一个新的线程来处理该客户端的请求。处理函数为`handle_client`,它会接收客户端发送的消息并回复一个确认消息,直到客户端断开连接。主函数中的`accept_clients`会一直循环接收客户端连接请求,直到程序结束。
阅读全文