这是服务端代码#define _WINSOCK_DEPRECATED_NO_WARNINGS #define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <stdlib.h> #include <string.h> #include <WinSock2.h> #ifndef MSG_NOSIGNAL #define MSG_NOSIGNAL 0 #endif #pragma comment(lib,"ws2_32.lib") SOCKET g_clientSockets[10]; int g_clientCount = 0; DWORD WINAPI ClientThread(LPVOID lpParam) { SOCKET clientSocket = (SOCKET)lpParam; char recvBuf[50], sendBuf[50]; while (1) { // 接收客户端消息并处理 int ret = recv(clientSocket, recvBuf, 50, 0); if (ret <= 0) { break; } printf("Received message from client: %s\n", recvBuf); // 转发消息给所有客户端 for (int i = 0; i < g_clientCount; i++) { if (g_clientSockets[i] != clientSocket) { send(g_clientSockets[i], recvBuf, strlen(recvBuf) + 1, 0); } } } // 关闭客户端套接字 closesocket(clientSocket); // 从全局变量中移除该客户端套接字 for (int i = 0; i < g_clientCount; i++) { if (g_clientSockets[i] == clientSocket) { g_clientCount--; memmove(&g_clientSockets[i], &g_clientSockets[i + 1], (g_clientCount - i) * sizeof(SOCKET)); break; } } return 0; } int main() { WORD wVersionRequested; WSADATA wsaData; int err; wVersionRequested = MAKEWORD(1, 1); err = WSAStartup(wVersionRequested, &wsaData); if (err != 0) { return -1; } if (LOBYTE(wsaData.wVersion) != 1 || HIBYTE(wsaData.wVersion) != 1) { WSACleanup(); return -1; } // 创建套接字并绑定到本地地址 SOCKET sockSrv = socket(AF_INET, SOCK_STREAM, 0); SOCKADDR_IN addrSrv; addrSrv.sin_family = AF_INET; addrSrv.sin_addr.S_un.S_addr = htonl(INADDR_ANY); addrSrv.sin_port = htons(6000); bind(sockSrv, (SOCKADDR*)&addrSrv, sizeof(SOCKADDR)); // 开始监听客户端连接请求 listen(sockSrv, 5); while (1) { // 接受客户端连接并处理消息 SOCKADDR_IN addrClient; int len = sizeof(SOCKADDR); SOCKET sockConn = accept(sockSrv, (SOCKADDR*)&addrClient, &len); // 将新连接的客户端套接字加入全局变量 g_clientSockets[g_clientCount++] = sockConn; // 创建新线程来处理该客户端的消息 HANDLE hThread = CreateThread(NULL, 0, ClientThread, &sockConn, 0, NULL); // 关闭线程句柄 CloseHandle(hThread); } closesocket(sockSrv); WSACleanup(); return 0; }
时间: 2024-04-27 22:20:32 浏览: 106
Define_Grid_Motion.zip_DEFINE_GRID_MOTION_fluent udf_fluent变形_f
5星 · 资源好评率100%
这是一个基于 Windows 平台的 TCP 服务器程序,它使用了 WinSock2 库提供的接口来完成网络通信。该程序创建了一个服务器套接字,绑定到本地地址并开始监听客户端连接请求。当有客户端连接时,它将客户端套接字加入全局变量并创建一个新的线程来处理该客户端的消息。当客户端发送消息时,该程序会将该消息转发给所有其他客户端。当客户端断开连接时,该程序会将该客户端套接字从全局变量中移除并关闭该套接字。
阅读全文