C++ TCP 服务端和客户端通信的例子
在此基础上,将服务端改为时刻在线文章来源地址https://www.toymoban.com/news/detail-854179.html
#include <iostream>
#include <winsock2.h>
#include <Ws2tcpip.h> // for inet_ntop
#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;
while (true) {
// 接受客户端连接
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;
// 从客户端接收消息
int valread;
if ((valread = recv(newSocket, buffer, sizeof(buffer), 0)) == SOCKET_ERROR) {
std::cerr << "Recv failed." << std::endl;
closesocket(newSocket);
closesocket(serverSocket);
WSACleanup();
return 1;
}
if (valread == 0) {
std::cout << "Client disconnected." << std::endl;
}
else {
std::cout << "Message from client: " << buffer << std::endl;
}
// 发送消息到客户端
if (send(newSocket, message, strlen(message), 0) == SOCKET_ERROR) {
std::cerr << "Send failed." << std::endl;
closesocket(newSocket);
closesocket(serverSocket);
WSACleanup();
return 1;
}
std::cout << "Message sent to client." << std::endl;
// 关闭套接字
closesocket(newSocket);
}
// 关闭服务器套接字
closesocket(serverSocket);
WSACleanup();
return 0;
}
文章来源:https://www.toymoban.com/news/detail-854179.html
到了这里,关于tcp服务端,时刻在线的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!