TCP服务端主动向客户端发送数据

C++ TCP 服务端和客户端通信的例子

在此基础上,要修改服务端代码,使其能够每秒向客户端发送当前时间,你需要添加一个循环,每次循环发送当前时间给客户端。同时,你需要在客户端代码中添加接收服务端发送的数据的逻辑。

以下是修改后的代码:

服务端代码:

cpp 复制代码
#include <iostream>
#include <winsock2.h>
#include <Ws2tcpip.h> // for inet_ntop
#include <ctime> // for time and localtime_s

#pragma comment(lib, "Ws2_32.lib")

#define PORT 8080

int main() {
    WSADATA wsaData;
    SOCKET serverSocket, newSocket;
    struct sockaddr_in serverAddr, clientAddr;
    int clientAddrLen = sizeof(clientAddr);
    char buffer[1024] = { 0 };
    const char* message = "Hello from server";

    // 初始化 Winsock
    if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) {
        std::cerr << "WSAStartup failed." << std::endl;
        return 1;
    }

    // 创建服务器套接字
    if ((serverSocket = socket(AF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET) {
        std::cerr << "Socket creation failed." << std::endl;
        WSACleanup();
        return 1;
    }

    // 设置服务器地址
    serverAddr.sin_family = AF_INET;
    serverAddr.sin_addr.s_addr = INADDR_ANY;
    serverAddr.sin_port = htons(PORT);

    // 将套接字绑定到服务器地址
    if (bind(serverSocket, (struct sockaddr*)&serverAddr, sizeof(serverAddr)) == SOCKET_ERROR) {
        std::cerr << "Bind failed." << std::endl;
        closesocket(serverSocket);
        WSACleanup();
        return 1;
    }

    // 监听连接
    if (listen(serverSocket, 5) == SOCKET_ERROR) {
        std::cerr << "Listen failed." << std::endl;
        closesocket(serverSocket);
        WSACleanup();
        return 1;
    }

    std::cout << "Server listening on port " << PORT << std::endl;

    // 接受客户端连接
    if ((newSocket = accept(serverSocket, (struct sockaddr*)&clientAddr, &clientAddrLen)) == INVALID_SOCKET) {
        std::cerr << "Accept failed." << std::endl;
        closesocket(serverSocket);
        WSACleanup();
        return 1;
    }

    // Convert client IP address to string
    char clientIP[INET_ADDRSTRLEN];
    inet_ntop(AF_INET, &clientAddr.sin_addr, clientIP, INET_ADDRSTRLEN);
    std::cout << "Connection accepted from " << clientIP << ":" << ntohs(clientAddr.sin_port) << std::endl;

    // 每秒向客户端发送当前时间
    while (true) {
        // 获取当前时间
        time_t currentTime = time(nullptr);
        struct tm localTime;
        localtime_s(&localTime, &currentTime);
        std::string timeString = asctime(&localTime);

        // 发送当前时间给客户端
        if (send(newSocket, timeString.c_str(), timeString.size(), 0) == SOCKET_ERROR) {
            std::cerr << "Send failed." << std::endl;
            closesocket(newSocket);
            closesocket(serverSocket);
            WSACleanup();
            return 1;
        }

        std::cout << "Message sent to client: " << timeString;
        Sleep(1000); // 等待1秒钟
    }

    // 关闭套接字
    closesocket(newSocket);
    closesocket(serverSocket);
    WSACleanup();

    return 0;
}

客户端代码:

cpp 复制代码
#include <iostream>
#include <winsock2.h>
#include <Ws2tcpip.h> // for inet_pton

#pragma comment(lib, "Ws2_32.lib")

#define PORT 8080
#define SERVER_IP "127.0.0.1"

int main() {
    WSADATA wsaData;
    SOCKET clientSocket;
    struct sockaddr_in serverAddr;
    char buffer[1024] = { 0 };

    // 初始化 Winsock
    if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) {
        std::cerr << "WSAStartup failed." << std::endl;
        return 1;
    }

    // 创建客户端套接字
    if ((clientSocket = socket(AF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET) {
        std::cerr << "Socket creation failed." << std::endl;
        WSACleanup();
        return 1;
    }

    // 设置服务器地址
    serverAddr.sin_family = AF_INET;
    inet_pton(AF_INET, SERVER_IP, &(serverAddr.sin_addr));
    serverAddr.sin_port = htons(PORT);

    // 连接到服务器
    if (connect(clientSocket, (struct sockaddr*)&serverAddr, sizeof(serverAddr)) == SOCKET_ERROR) {
        std::cerr << "Connect failed." << std::endl;
        closesocket(clientSocket);
        WSACleanup();
        return 1;
    }

    std::cout << "Connected to server." << std::endl;

    // 接收来自服务器的消息
    int valread;
    while ((valread = recv(clientSocket, buffer, sizeof(buffer), 0)) > 0) {
        std::cout << "Message from server: " << buffer << std::endl;
        memset(buffer, 0, sizeof(buffer)); // 清空缓冲区
    }

    if (valread == 0) {
        std::cout << "Server disconnected." << std::endl;
    } else {
        std::cerr << "Recv failed." << std::endl;
    }

    // 关闭套接字
    closesocket(clientSocket);
    WSACleanup();

    return 0;
}

这样修改后,服务端每秒钟向客户端发送当前时间,而客户端接收并打印出来。

相关推荐
长弓三石41 分钟前
鸿蒙网络编程系列44-仓颉版HttpRequest上传文件示例
前端·网络·华为·harmonyos·鸿蒙
xianwu5431 小时前
反向代理模块
linux·开发语言·网络·git
follycat1 小时前
[极客大挑战 2019]HTTP 1
网络·网络协议·http·网络安全
earthzhang20212 小时前
《深入浅出HTTPS》读书笔记(5):随机数
网络协议·http·https
xiaoxiongip6662 小时前
HTTP 和 HTTPS
网络·爬虫·网络协议·tcp/ip·http·https·ip
JaneJiazhao2 小时前
HTTPSOK:SSL/TLS证书自动续期工具
服务器·网络协议·ssl
JaneJiazhao2 小时前
HTTPSOK:智能SSL证书管理的新选择
网络·网络协议·ssl
CXDNW2 小时前
【网络面试篇】HTTP(2)(笔记)——http、https、http1.1、http2.0
网络·笔记·http·面试·https·http2.0
无所谓จุ๊บ3 小时前
树莓派开发相关知识十 -小试服务器
服务器·网络·树莓派
道法自然04023 小时前
Ethernet 系列(8)-- 基础学习::ARP
网络·学习·智能路由器