使用boost1.70,创建一个线程,监听socket接受数据
时间: 2024-03-27 15:36:28 浏览: 120
Socket 监听
好的,使用boost创建一个线程监听socket接受数据,具体步骤如下:
1. 引入boost库和相关头文件。例如:
```cpp
#include <boost/asio.hpp>
#include <boost/thread.hpp>
```
2. 创建一个`io_service`对象和一个`tcp::acceptor`对象,用于监听socket连接请求。例如:
```cpp
boost::asio::io_service io_service;
boost::asio::ip::tcp::acceptor acceptor(io_service,
boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), 8888));
```
3. 创建一个新线程,使用`async_accept()`方法接收客户端连接请求,并返回一个新的`tcp::socket`对象。例如:
```cpp
void accept_handler(const boost::system::error_code& error,
boost::asio::ip::tcp::socket socket) {
if (!error) {
std::cout << "New connection: " << socket.remote_endpoint() << std::endl;
// 创建一个新线程
boost::thread t(boost::bind(&recv_handler, boost::ref(socket)));
// 继续监听连接请求
acceptor.async_accept(boost::bind(&accept_handler,
boost::asio::placeholders::error, socket));
}
}
acceptor.async_accept(boost::bind(&accept_handler,
boost::asio::placeholders::error, boost::asio::ip::tcp::socket(io_service)));
```
4. 在新线程中使用`async_read()`方法接收客户端发送的数据。例如:
```cpp
void recv_handler(boost::asio::ip::tcp::socket& socket) {
boost::asio::streambuf buffer;
boost::system::error_code error;
while (true) {
boost::asio::read(socket, buffer, boost::asio::transfer_at_least(1), error);
if (error) {
std::cout << "Error: " << error.message() << std::endl;
break;
}
std::string message(boost::asio::buffers_begin(buffer.data()),
boost::asio::buffers_end(buffer.data()));
std::cout << "Received data: " << message << std::endl;
buffer.consume(buffer.size());
}
}
```
这样,就可以使用boost创建一个线程监听socket接收数据了。注意要在程序结束时关闭socket连接。完整的代码如下:
```cpp
#include <boost/asio.hpp>
#include <boost/thread.hpp>
#include <iostream>
void accept_handler(const boost::system::error_code& error,
boost::asio::ip::tcp::socket socket);
void recv_handler(boost::asio::ip::tcp::socket& socket) {
boost::asio::streambuf buffer;
boost::system::error_code error;
while (true) {
boost::asio::read(socket, buffer, boost::asio::transfer_at_least(1), error);
if (error) {
std::cout << "Error: " << error.message() << std::endl;
break;
}
std::string message(boost::asio::buffers_begin(buffer.data()),
boost::asio::buffers_end(buffer.data()));
std::cout << "Received data: " << message << std::endl;
buffer.consume(buffer.size());
}
}
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(), 8888));
acceptor.async_accept(boost::bind(&accept_handler,
boost::asio::placeholders::error, boost::asio::ip::tcp::socket(io_service)));
io_service.run();
return 0;
}
void accept_handler(const boost::system::error_code& error,
boost::asio::ip::tcp::socket socket) {
if (!error) {
std::cout << "New connection: " << socket.remote_endpoint() << std::endl;
// 创建一个新线程
boost::thread t(boost::bind(&recv_handler, boost::ref(socket)));
// 继续监听连接请求
acceptor.async_accept(boost::bind(&accept_handler,
boost::asio::placeholders::error, socket));
}
}
```
阅读全文