本文主要是介绍TCP服务端主动向客户端发送数据,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
C++ TCP 服务端和客户端通信的例子
在此基础上,要修改服务端代码,使其能够每秒向客户端发送当前时间,你需要添加一个循环,每次循环发送当前时间给客户端。同时,你需要在客户端代码中添加接收服务端发送的数据的逻辑。
以下是修改后的代码:
服务端代码:
#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 8080int 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";// 初始化 Winsockif (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 stringchar 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, ¤tTime);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;
}
客户端代码:
#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 };// 初始化 Winsockif (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;
}
这样修改后,服务端每秒钟向客户端发送当前时间,而客户端接收并打印出来。
这篇关于TCP服务端主动向客户端发送数据的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!