windowsC++创建一个server端的类,ip为127.0.0.1,端口7799。这个server端用于接收client的信息
时间: 2024-09-23 09:03:25 浏览: 39
在Windows环境下使用C++创建一个服务器,通常我们会利用Socket编程技术。下面是一个简单的例子,展示如何创建一个Server类,监听IP地址127.0.0.1和端口号7799:
```cpp
#include <iostream>
#include <winsock2.h>
#include <ws2tcpip.h>
#pragma comment(lib, "ws2_32.lib")
class Server {
private:
struct addrinfo hints;
SOCKET server_socket;
char buffer[256];
public:
Server(int port)
: hints(ai_family = AF_INET, ai_socktype = SOCK_STREAM, ai_flags = AI_PASSIVE),
server_socket(INVALID_SOCKET) {
ZeroMemory(&hints, sizeof(hints));
// 获取本地回环地址
hints.ai_addr = reinterpret_cast<struct sockaddr_in*>(&hints.sin6_addr);
hints.ai_addrlen = sizeof(struct sockaddr_in);
// 创建套接字
if (WSAStartup(MAKEWORD(2, 2), &wsaData)) {
std::cerr << "WSAStartup failed" << std::endl;
return;
}
server_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (server_socket == INVALID_SOCKET) {
std::cerr << "Socket creation failed" << std::endl;
WSACleanup();
return;
}
// 绑定服务器到指定端口
if (bind(server_socket, (struct sockaddr*)&hints, sizeof(hints)) != 0) {
std::cerr << "Bind failed: " << WSAGetLastError() << std::endl;
closesocket(server_socket);
WSACleanup();
return;
}
// 开始监听连接
if (listen(server_socket, SOMAXCONN) != 0) {
std::cerr << "Listen failed: " << WSAGetLastError() << std::endl;
closesocket(server_socket);
WSACleanup();
return;
}
std::cout << "Server started on 127.0.0.1:7799" << std::endl;
// 接收客户端连接并处理请求
accept_client();
}
~Server() {
if (server_socket != INVALID_SOCKET) {
closesocket(server_socket);
}
WSACleanup();
}
private:
void accept_client() {
while (true) {
SOCKET client_socket = accept(server_socket, nullptr, nullptr);
if (client_socket == INVALID_SOCKET) break;
std::string message;
do {
recv(client_socket, buffer, sizeof(buffer), 0);
message += buffer;
} while (recv(client_socket, buffer, sizeof(buffer), MSG_PEEK) > 0);
std::cout << "Received from client: " << message << std::endl; // 这里只是打印信息,实际可以解析消息并处理
send(client_socket, "Server received your message", strlen("Server received your message"), 0);
closesocket(client_socket);
}
}
};
int main() {
try {
Server server(7799);
server_thread.join();
} catch (...) {
std::cerr << "An error occurred." << std::endl;
}
return 0;
}
```
在这个示例中,`Server` 类初始化了一个TCP服务器,等待来自127.0.0.1的连接。当有客户端连接时,它接受数据、读取数据,并向客户端发送一条确认消息。
阅读全文