C++创建一个Server端类,用来接受Client的数据并将消息打印出来
时间: 2024-09-21 22:02:36 浏览: 37
C++类中创建多线程实现本地和远程打印
要在C++中创建一个Server端类,可以使用套接字编程来实现。以下是一个简单的示例,展示了如何创建一个Server端类,用于接收客户端的数据并将消息打印出来:
```cpp
#include <iostream>
#include <string>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
class Server {
public:
Server(int port) {
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd == -1) {
std::cerr << "创建套接字失败" << std::endl;
exit(1);
}
sockaddr_in server_addr;
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(port);
server_addr.sin_addr.s_addr = INADDR_ANY;
if (bind(sockfd, (struct sockaddr *)&server_addr, sizeof(server_addr)) == -1) {
std::cerr << "绑定套接字失败" << std::endl;
exit(1);
}
if (listen(sockfd, 5) == -1) {
std::cerr << "监听套接字失败" << std::endl;
exit(1);
}
}
void acceptClients() {
while (true) {
sockaddr_in client_addr;
socklen_t client_addr_len = sizeof(client_addr);
int new_sockfd = accept(sockfd, (struct sockaddr *)&client_addr, &client_addr_len);
if (new_sockfd == -1) {
std::cerr << "接受客户端连接失败" << std::endl;
continue;
}
std::cout << "客户端已连接" << std::endl;
handleClient(new_sockfd);
}
}
private:
int sockfd;
void handleClient(int client_sockfd) {
char buffer[1024];
while (true) {
ssize_t bytes_received = recv(client_sockfd, buffer, sizeof(buffer), 0);
if (bytes_received <= 0) {
std::cout << "客户端断开连接" << std::endl;
break;
}
buffer[bytes_received] = '\0';
std::cout << "收到消息: " << buffer << std::endl;
}
close(client_sockfd);
}
};
int main() {
int port = 8080;
Server server(port);
server.acceptClients();
return 0;
}
```
这个示例中,我们创建了一个名为`Server`的类,它包含一个构造函数,用于初始化套接字并绑定到指定的端口。`acceptClients`方法用于监听客户端连接,并在有新的连接时调用`handleClient`方法处理客户端发送的数据。`handleClient`方法接收客户端发送的消息并将其打印出来。
阅读全文