windows C++创建一个服务端类,ip为127.0.0.1 端口为7799,并分为.h和.cpp,并告诉我如何调用,其中所有的打印log都改成udebug
时间: 2024-09-20 11:13:44 浏览: 38
在Windows上使用C++创建一个服务器类,监听IP地址`127.0.0.1`和端口号`7799`,通常会涉及定义一个Server类,包含网络套接字操作以及客户端连接处理的功能。这里是一个基本的步骤:
首先,在`.h`文件(如`Server.h`)中,定义Server类及其接口:
```cpp
// Server.h
#include <winsock2.h>
#include <iostream>
class Server {
public:
Server();
~Server();
bool start(int port);
void handleClientConnection(std::string client_ip, int client_port);
private:
WSADATA wsaData;
SOCKET serverSocket;
u_long iOne = 1;
};
```
然后,在`.cpp`文件(如`Server.cpp`)中,实现类的具体功能:
```cpp
// Server.cpp
#include "Server.h"
Server::Server() {
if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) {
std::cerr << "Error initializing Winsock" << std::endl;
return;
}
serverSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (serverSocket == INVALID_SOCKET) {
std::cerr << "Failed to create socket" << std::endl;
WSACleanup();
return;
}
sockaddr_in serverAddr;
serverAddr.sin_family = AF_INET;
serverAddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK); // IP address 127.0.0.1
serverAddr.sin_port = htons(7799);
if (bind(serverSocket, reinterpret_cast<SOCKADDR*>(&serverAddr), sizeof(serverAddr)) != 0) {
std::cerr << "Failed to bind socket" << std::endl;
closesocket(serverSocket);
WSACleanup();
return;
}
}
bool Server::start(int port) {
if (listen(serverSocket, 5) != 0) { // listen for up to 5 connections
std::cerr << "Failed to listen on the socket" << std::endl;
return false;
}
std::cout << "Server started, listening on 127.0.0.1:" << port << std::endl;
return true;
}
void Server::handleClientConnection(std::string client_ip, int client_port) {
// Your client connection handling code here...
std::cout << "Accepted connection from " << client_ip << ":" << client_port << std::endl;
// To use udebug instead of cout, replace all instances with your custom logging function
// For example:
LogUDEBUG("Received message from " << client_ip);
}
```
最后,在需要的地方创建并启动这个服务,例如main函数中:
```cpp
int main() {
try {
Server myServer;
if (!myServer.start(7799)) {
return 1;
}
// Accept incoming client connections and pass them to handleClientConnection()
while (true) {
sockaddr_in clientAddr;
socklen_t addrLen = sizeof(clientAddr);
SOCKET clientSocket = accept(serverSocket, (SOCKADDR*)&clientAddr, &addrLen);
if (clientSocket == INVALID_SOCKET) {
break;
}
char ipBuffer[INET_ADDRSTRLEN];
inet_ntop(AF_INET, &clientAddr.sin_addr, ipBuffer, INET_ADDRSTRLEN);
int clientPort = ntohs(clientAddr.sin_port);
std::string clientIp(ipBuffer);
myServer.handleClientConnection(clientIp, clientPort);
closesocket(clientSocket);
}
} catch (std::exception& e) {
std::cerr << "Error: " << e.what() << std::endl;
}
WSACleanup(); // Always clean up when done
return 0;
}
```
为了调用这个服务,你需要链接到Winsock库,并运行包含`main()`函数的程序。
阅读全文