windows系统下 使用C++创建一个Server端的类,用来接收Client的数据并将消息打印出来
时间: 2024-09-20 20:08:14 浏览: 52
UDP_DEMO.rar_DEMO_UDP C++ 数据_UDP接收
在Windows系统下,使用C++创建一个Server端的类来接收Client的数据并将消息打印出来,可以使用Winsock库。以下是一个简单的示例:
```cpp
#include <iostream>
#include <winsock2.h>
#pragma comment(lib, "ws2_32.lib")
class Server {
public:
Server() {
WSADATA wsaData;
if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) {
std::cerr << "WSAStartup failed: " << WSAGetLastError() << std::endl;
exit(1);
}
}
~Server() {
WSACleanup();
}
void start(int port) {
SOCKET listenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (listenSocket == INVALID_SOCKET) {
std::cerr << "socket failed: " << WSAGetLastError() << std::endl;
exit(1);
}
sockaddr_in serverAddr;
serverAddr.sin_family = AF_INET;
serverAddr.sin_addr.s_addr = INADDR_ANY;
serverAddr.sin_port = htons(port);
if (bind(listenSocket, (sockaddr*)&serverAddr, sizeof(serverAddr)) == SOCKET_ERROR) {
std::cerr << "bind failed: " << WSAGetLastError() << std::endl;
exit(1);
}
if (listen(listenSocket, SOMAXCONN) == SOCKET_ERROR) {
std::cerr << "listen failed: " << WSAGetLastError() << std::endl;
exit(1);
}
std::cout << "Server is listening on port " << port << std::endl;
while (true) {
sockaddr_in clientAddr;
int clientAddrSize = sizeof(clientAddr);
SOCKET clientSocket = accept(listenSocket, (sockaddr*)&clientAddr, &clientAddrSize);
if (clientSocket == INVALID_SOCKET) {
std::cerr << "accept failed: " << WSAGetLastError() << std::endl;
continue;
}
char buffer[1024];
int bytesReceived = recv(clientSocket, buffer, sizeof(buffer), 0);
if (bytesReceived > 0) {
buffer[bytesReceived] = '\0';
std::cout << "Received message: " << buffer << std::endl;
}
closesocket(clientSocket);
}
closesocket(listenSocket);
}
};
int main() {
Server server;
server.start(8080);
return 0;
}
```
这个示例中,我们创建了一个名为`Server`的类,它在构造函数中初始化Winsock库,并在析构函数中清理资源。`start`方法用于启动服务器并监听指定端口。当客户端连接时,服务器接收数据并将其打印到控制台。注意,这个示例没有处理多个客户端连接的情况,也没有实现错误处理和异常处理。在实际项目中,你可能需要根据需求进行相应的修改和扩展。
阅读全文