windowsC++创建一个server端的类,ip为127.0.0.1,端口7799。这个server端用于接收client的信息,写成.h和.cpp的格式
时间: 2024-09-23 18:08:57 浏览: 48
在Windows上使用C++创建一个服务器端程序,通常会涉及套接字编程。首先,你需要包含必要的头文件,并定义一个Server类。这里是一个简单的.h和.cpp文件示例:
**Server.h**
```cpp
#pragma once
#include <winsock2.h>
#include <ws2tcpip.h>
#include <iostream>
#include <string>
class Server {
public:
Server(std::string ipAddress, int port);
void start();
private:
sockaddr_in serverAddr;
SOCKET serverSocket;
};
```
**Server.cpp**
```cpp
#include "Server.h"
#include <cstring>
#include <thread>
#include <vector>
Server::Server(const std::string& ipAddress, int port) {
WSADATA wsaData;
if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) {
throw std::runtime_error("Failed to initialize Winsock");
}
serverAddr.sin_family = AF_INET;
serverAddr.sin_port = htons(port);
inet_pton(AF_INET, ipAddress.c_str(), &serverAddr.sin_addr);
if ((serverSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == INVALID_SOCKET) {
closesocket(serverSocket);
WSACleanup();
throw std::runtime_error("Failed to create a socket");
}
if (bind(serverSocket, reinterpret_cast<SOCKADDR*>(&serverAddr), sizeof(serverAddr)) != 0) {
closesocket(serverSocket);
WSACleanup();
throw std::runtime_error("Failed to bind to the address");
}
listen(serverSocket, SOMAXCONN); // Max connections
}
void Server::start() {
std::cout << "Server started on " << inet_ntoa(serverAddr.sin_addr) << ":" << ntohs(serverAddr.sin_port) << std::endl;
while (true) {
sockaddr_in clientAddr;
socklen_t addrSize = sizeof(clientAddr);
SOCKET clientSocket = accept(serverSocket, (struct sockaddr*)&clientAddr, &addrSize);
if (clientSocket == INVALID_SOCKET) {
perror("accept failed");
continue;
}
std::thread handler([this, clientSocket] {
char buffer[1024];
DWORD bytesRead = recv(clientSocket, buffer, sizeof(buffer), 0);
if (bytesRead > 0) {
std::cout << "Received from client: " << buffer << std::endl;
}
closesocket(clientSocket);
});
handler.detach(); // Detach thread for efficient handling
}
}
// 示例如何创建并启动服务器
int main() {
try {
Server server("127.0.0.1", 7799);
server.start();
} catch (const std::exception& e) {
std::cerr << "Error: " << e.what() << std::endl;
}
return 0;
}
```
在这个例子中,`Server`类包含了创建socket、绑定到指定地址、监听连接以及处理客户端请求的功能。当你运行`main`函数时,它会启动一个服务器。
阅读全文