基于boost1.60,开启一个线程,作为服务器,使用socket进行端口监听
时间: 2024-03-13 20:46:48 浏览: 25
以下是一个使用 Boost 库的 asio 模块的例子,用于在本地监听指定端口的连接请求:
```c++
#include <iostream>
#include <boost/asio.hpp>
#include <boost/thread.hpp>
using namespace boost::asio;
using namespace std;
// 服务器地址
const string host = "127.0.0.1";
// 监听端口号
const int port = 8888;
void handle_client(shared_ptr<ip::tcp::socket> client_socket)
{
try
{
// 接收客户端发来的数据
boost::asio::streambuf buffer;
read_until(*client_socket, buffer, "\n");
string data = buffer_cast<const char*>(buffer.data());
cout << "Received: " << data << endl;
// 发送响应数据给客户端
string response = "Hello, Client!\n";
write(*client_socket, buffer(response));
// 关闭连接
client_socket->close();
}
catch (exception& e)
{
cerr << "Exception in thread: " << e.what() << endl;
}
}
void start_server()
{
try
{
// 创建一个 I/O 上下文对象
io_context io;
// 创建一个 TCP 套接字对象
ip::tcp::socket server_socket(io);
// 绑定地址和端口号
ip::tcp::endpoint endpoint(ip::address::from_string(host), port);
server_socket.bind(endpoint);
// 监听端口,等待连接请求
server_socket.listen();
cout << "Server started on port " << port << endl;
while (true)
{
// 接收客户端连接请求
shared_ptr<ip::tcp::socket> client_socket(new ip::tcp::socket(io));
server_socket.accept(*client_socket);
cout << "Accepted connection from " << client_socket->remote_endpoint().address().to_string() << endl;
// 创建一个线程来处理客户端连接请求
boost::thread t(boost::bind(handle_client, client_socket));
t.detach();
}
}
catch (exception& e)
{
cerr << "Exception: " << e.what() << endl;
}
}
int main()
{
start_server();
return 0;
}
```
这个例子中,我们首先创建了一个 I/O 上下文对象和一个 TCP 套接字对象,并绑定了地址和端口号。然后使用 `listen()` 方法开始监听端口,并在一个循环中等待客户端连接请求。当有客户端连接请求时,我们创建一个新的线程来处理该请求,并在其中执行 `handle_client()` 函数。在这个函数中,我们可以处理客户端发送的数据,并向客户端发送响应数据。最后,我们关闭连接,结束线程。
需要注意的是,在 Boost 库的 asio 模块中,使用 `shared_ptr` 来管理套接字对象的生命周期,以确保在多线程环境下正确释放资源。同时,使用 `read_until()` 和 `write()` 方法来读取和写入数据。