windows TCP Server demo

TcpServer.h

cpp 复制代码
#ifndef TCPSERVER_H
#define TCPSERVER_H

#include <iostream>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <vector>
#include <map>
#include <string>
#include <ctime>

// 引入静态链接库
#pragma comment(lib, "ws2_32.lib")

class TcpServer {
public:
    TcpServer();
    ~TcpServer();

    // 启动服务器,监听指定端口
    bool start(int port);

    // 停止服务器
    void stop();

    // 发送数据给指定客户端
    int sendData(SOCKET clientSocket, const char* data, int dataLength);

    // 处理服务器业务逻辑,通常在循环中调用
    void handle();

private:
    SOCKET listenSocket;
    std::vector<SOCKET> clientSockets;
    std::map<SOCKET, std::time_t> clientLastHeartbeatTime;
    int heartbeatInterval;  // 心跳包间隔时间(秒)

    // 设置套接字为非阻塞模式
    bool setSocketNonBlocking(SOCKET socket);

    // 接受新的客户端连接
    void acceptNewClients();

    // 接收客户端数据
    void receiveClientData();

    // 发送心跳包给客户端,并检测客户端响应
    void sendHeartbeatsAndCheck();

    // 移除已断开连接的客户端
    void removeDisconnectedClients();
};

#endif

TcpServer.cpp

cpp 复制代码
#include "TcpServer.h"

// 构造函数,初始化相关成员变量
TcpServer::TcpServer() : listenSocket(INVALID_SOCKET), heartbeatInterval(5) {
    WSADATA wsaData;
    int result = WSAStartup(MAKEWORD(2, 2), &wsaData);
    if (result != 0) {
        std::cerr << "WSAStartup failed: " << result << std::endl;
    }
}

// 析构函数,关闭套接字并清理WinSock环境
TcpServer::~TcpServer() {
    stop();
    WSACleanup();
}

// 启动服务器,监听指定端口
bool TcpServer::start(int port) {
    listenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (listenSocket == INVALID_SOCKET) {
        std::cerr << "Socket creation failed: " << WSAGetLastError() << std::endl;
        return false;
    }

    if (!setSocketNonBlocking(listenSocket)) {
        std::cerr << "Failed to set listen socket non-blocking" << std::endl;
        closesocket(listenSocket);
        return false;
    }

    sockaddr_in serverAddr;
    serverAddr.sin_family = AF_INET;
    serverAddr.sin_addr.s_addr = INADDR_ANY;
    serverAddr.sin_port = htons(port);
    int result = bind(listenSocket, (sockaddr*)&serverAddr, sizeof(serverAddr));
    if (result == SOCKET_ERROR) {
        std::cerr << "Bind failed: " << WSAGetLastError() << std::endl;
        closesocket(listenSocket);
        return false;
    }

    result = listen(listenSocket, SOMAXCONN);
    if (result == SOCKET_ERROR) {
        std::cerr << "Listen failed: " << WSAGetLastError() << std::endl;
        closesocket(listenSocket);
        return false;
    }

    return true;
}

// 停止服务器
void TcpServer::stop()
{
    if (listenSocket != INVALID_SOCKET) {
        closesocket(listenSocket);
        listenSocket = INVALID_SOCKET;
    }

    for (SOCKET clientSocket : clientSockets) {
        closesocket(clientSocket);
    }
    clientSockets.clear();
    clientLastHeartbeatTime.clear();
}

// 设置套接字为非阻塞模式
bool TcpServer::setSocketNonBlocking(SOCKET socket) {
    u_long iMode = 1;
    int result = ioctlsocket(socket, FIONBIO, &iMode);
    if (result == SOCKET_ERROR) {
        std::cerr << "ioctlsocket failed: " << WSAGetLastError() << std::endl;
        return false;
    }
    return true;
}

// 发送数据给指定客户端
int TcpServer::sendData(SOCKET clientSocket, const char* data, int dataLength) {
    if (clientSocket == INVALID_SOCKET) 
    {
        std::cerr << "Invalid client socket, cannot send data" << std::endl;
        return SOCKET_ERROR;
    }

    int totalBytesSent = 0;
    while (totalBytesSent < dataLength) 
    {
        int bytesSent = ::send(clientSocket, data + totalBytesSent, dataLength - totalBytesSent, 0);
        if (bytesSent == SOCKET_ERROR)
        {
            if (WSAGetLastError() == WSAEWOULDBLOCK) 
            {
                // 暂时无法发送,等待下次尝试
                continue;
            }
            return SOCKET_ERROR;
        }
        totalBytesSent += bytesSent;
    }
    return totalBytesSent;
}

// 接受新的客户端连接
void TcpServer::acceptNewClients() {
    SOCKET newClientSocket = accept(listenSocket, NULL, NULL);
    if (newClientSocket == INVALID_SOCKET) {
        if (WSAGetLastError() != WSAEWOULDBLOCK) {
            std::cerr << "Accept failed: " << WSAGetLastError() << std::endl;
        }
        return;
    }

    if (!setSocketNonBlocking(newClientSocket)) {
        std::cerr << "Failed to set client socket non-blocking" << std::endl;
        closesocket(newClientSocket);
        return;
    }

    clientSockets.push_back(newClientSocket);
    clientLastHeartbeatTime[newClientSocket] = std::time(nullptr);
}

// 接收客户端数据
void TcpServer::receiveClientData()
{
    std::vector<SOCKET> socketsToRemove;
    for (size_t i = 0; i < clientSockets.size(); ++i)
    {
        SOCKET clientSocket = clientSockets[i];
        char buffer[1024];
        int bytesReceived = ::recv(clientSocket, buffer, sizeof(buffer), 0);
        if (bytesReceived == SOCKET_ERROR) 
        {
            if (WSAGetLastError() == WSAEWOULDBLOCK) 
            {
                // 暂时无数据可读,继续检查下一个客户端
                continue;
            }
            socketsToRemove.push_back(clientSocket);
        }
        else if (bytesReceived == 0)
        {
            // 客户端关闭连接
            socketsToRemove.push_back(clientSocket);
        }
        else
        {
            buffer[bytesReceived] = '\0';
            std::string receivedData(buffer);
            // 在这里可以根据接收到的数据进行具体业务逻辑处理,比如解析命令等
            std::cout << "Received from client " << clientSocket << ": " << receivedData << std::endl;
            clientLastHeartbeatTime[clientSocket] = std::time(nullptr);
            std::string heartbeatData = "recv ok:";
            int sentBytes = sendData(clientSocket, heartbeatData.c_str(), heartbeatData.length());

        }
    }

    // 移除已断开连接的客户端(此处调用下面定义的 removeDisconnectedClients 函数,无参数传递)
    removeDisconnectedClients();
}

// 发送心跳包给客户端,并检测客户端响应
void TcpServer::sendHeartbeatsAndCheck()
{
    const char* heartbeatData = "HEARTBEAT";  // 简单的心跳包内容,可自定义
    int dataLength = strlen(heartbeatData);
    std::vector<SOCKET> socketsToRemove;
    for (auto& clientPair : clientLastHeartbeatTime) 
    {
        SOCKET clientSocket = clientPair.first;
        std::time_t& lastHeartbeatTime = clientPair.second;
        std::time_t currentTime = std::time(nullptr);
        if (currentTime - lastHeartbeatTime > heartbeatInterval) 
        {
            // 超过心跳间隔时间没收到心跳响应,认为客户端连接异常
            socketsToRemove.push_back(clientSocket);
            continue;
        }

        int sentBytes = sendData(clientSocket, heartbeatData, dataLength);
        if (sentBytes == SOCKET_ERROR) {
            // 发送心跳包失败,认为客户端连接可能有问题
            socketsToRemove.push_back(clientSocket);
            continue;
        }

        char responseBuffer[1024];
        int receivedBytes = ::recv(clientSocket, responseBuffer, sizeof(responseBuffer), 0);
        if (receivedBytes == SOCKET_ERROR)
        {
            if (WSAGetLastError() == WSAEWOULDBLOCK)
            {
                // 暂时无数据可读,等待下次检测
                continue;
            }
            socketsToRemove.push_back(clientSocket);
            continue;
        }
        else if (receivedBytes == 0)
        {
            // 客户端关闭连接
            socketsToRemove.push_back(clientSocket);
            continue;
        }
        responseBuffer[receivedBytes] = '\0';
        std::string responseData(responseBuffer);
        // 在这里可以根据客户端对心跳包的响应进行进一步判断和处理,比如验证响应内容是否正确等
        if (responseData != "HEARTBEAT_RESPONSE")
        {  // 假设正确响应内容为 HEARTBEAT_RESPONSE
            socketsToRemove.push_back(clientSocket);
            continue;
        }

        lastHeartbeatTime = currentTime;
    }

    // 移除已断开连接或异常的客户端(此处调用下面定义的 removeDisconnectedClients 函数,无参数传递)
    removeDisconnectedClients();
}

// 移除已断开连接的客户端(更新函数定义,无参数)
void TcpServer::removeDisconnectedClients() 
{
    std::vector<SOCKET> socketsToRemove;
    for (size_t i = 0; i < clientSockets.size(); ++i)
    {
        SOCKET clientSocket = clientSockets[i];
        // 检查是否已经判定为需要移除(比如在前面接收数据或心跳检测环节标记为要移除)
        if (clientLastHeartbeatTime.find(clientSocket) == clientLastHeartbeatTime.end()) 
        {
            socketsToRemove.push_back(clientSocket);
        }
    }

    for (SOCKET socketToRemove : socketsToRemove)
    {
        auto it = std::find(clientSockets.begin(), clientSockets.end(), socketToRemove);
        if (it != clientSockets.end()) {
            clientSockets.erase(it);
            clientLastHeartbeatTime.erase(socketToRemove);
        }
    }
}

// 处理服务器业务逻辑,通常在循环中调用
void TcpServer::handle() 
{
    acceptNewClients();
    receiveClientData();
    sendHeartbeatsAndCheck();
    removeDisconnectedClients();
}

main.cpp

cpp 复制代码
#include "TcpServer.h"

int main() {
    TcpServer server;
    if (server.start(8080)) {
        while (true) {
            server.handle();
            // 可以在这里添加适当的延时,避免过于频繁地循环处理,消耗过多CPU资源
            Sleep(100);
        }
    }
    return 0;
}
相关推荐
群联云防护小杜7 小时前
防范TCP攻击:策略与实践
网络·网络协议·tcp/ip
亓才孓8 小时前
[计算机网络]IP地址推行的“书同文,车同轨”
网络·tcp/ip·计算机网络·软件工程
小狮子安度因8 小时前
DPDK用户态协议栈-TCP Posix API 2
网络·网络协议·tcp/ip
IpdataCloud8 小时前
在 Linux 和 Windows 操作系统下查询局域网IP
linux·运维·tcp/ip
xinxin88229 小时前
恢复删除的文件:6个免费Windows电脑数据恢复软件
人工智能·windows·智能手机·pdf·电脑·笔记本电脑·开源软件
小奥超人10 小时前
PPT技巧:将幻灯片里的图片背景设置为透明
windows·经验分享·microsoft·powerpoint·办公技巧
CodeGrindstone13 小时前
Muduo网络库解析 ---线程模块
网络·c++·tcp/ip
乌龟跌倒14 小时前
运输层8——TCP连接和释放
网络·网络协议·tcp/ip
大明湖的狗凯.14 小时前
HTTP 常见状态码解析
网络·网络协议·http