win32 Socket服务端封装类
时间: 2023-12-08 13:06:06 浏览: 145
下面是一个使用WinSock库封装的简单Win32 Socket服务端类的示例:
```cpp
#include <iostream>
#include <string>
#include <WinSock2.h>
#pragma comment(lib, "ws2_32.lib")
class SocketServer {
public:
SocketServer(int port) : serverPort(port), serverSocket(INVALID_SOCKET) {
if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) {
std::cerr << "Failed to initialize WinSock" << std::endl;
throw;
}
serverSocket = socket(AF_INET, SOCK_STREAM, 0);
if (serverSocket == INVALID_SOCKET) {
std::cerr << "Failed to create socket" << std::endl;
WSACleanup();
throw;
}
serverAddr.sin_family = AF_INET;
serverAddr.sin_addr.s_addr = INADDR_ANY;
serverAddr.sin_port = htons(serverPort);
if (bind(serverSocket, (struct sockaddr*)&serverAddr, sizeof(serverAddr)) == SOCKET_ERROR) {
std::cerr << "Bind failed with error" << WSAGetLastError() << std::endl;
closesocket(serverSocket);
WSACleanup();
throw;
}
if (listen(serverSocket, SOMAXCONN) == SOCKET_ERROR) {
std::cerr << "Listen failed with error" << WSAGetLastError() << std::endl;
closesocket(serverSocket);
WSACleanup();
throw;
}
}
~SocketServer() {
closesocket(serverSocket);
WSACleanup();
}
void startListening() {
struct sockaddr_in clientAddr;
int clientAddrLen = sizeof(clientAddr);
while (true) {
SOCKET clientSocket = accept(serverSocket, (struct sockaddr*)&clientAddr, &clientAddrLen);
if (clientSocket == INVALID_SOCKET) {
std::cerr << "Accept failed with error" << WSAGetLastError() << std::endl;
closesocket(serverSocket);
WSACleanup();
return;
}
std::cout << "Client connected" << std::endl;
// 处理客户端请求
std::string response = "Hello, client!";
send(clientSocket, response.c_str(), response.length(), 0);
// 关闭客户端连接
closesocket(clientSocket);
std::cout << "Client disconnected" << std::endl;
}
}
private:
int serverPort;
WSADATA wsaData;
SOCKET serverSocket;
SOCKADDR_IN serverAddr;
};
int main() {
SocketServer server(8080);
server.startListening();
return 0;
}
```
这个示例演示了一个简单的Win32 Socket服务端类。它在构造函数中初始化WinSock库,创建套接字并绑定到指定的端口。然后,在`startListening`方法中,它会接受客户端连接,处理客户端请求,并发送响应。每个客户端连接完成后,套接字会被关闭。你可以根据需要扩展该类以满足特定的需求。
阅读全文