慢慢修改:
#include <winsock.h> #include <stdio.h> #include <string> #define PORT 5010 #define MSGSIZE 1024 int BytesSum = 0; #pragma comment(lib, "ws2_32.lib") DWORD WINAPI WorkerThread(LPVOID lpParameter); void InitWinSocket() { WSADATA wsaData; WSAStartup(0x0202, &wsaData); } #define ListenQ 10 int main() { InitWinSocket(); SOCKET lListenFD, lClientSocket[FD_SetSize]; lListenFD = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); SOCKADDR_IN local, client; // Bind local.sin_addr.S_un.S_addr = htonl(INADDR_ANY); local.sin_family = AF_INET; local.sin_port = htons(PORT); bind(lListenFD, (struct sockaddr *)&local, sizeof(SOCKADDR_IN)); // Listen listen(lListenFD, ListenQ); int lTotalConn = 0; SOCKET lCliSocketArr[FD_SETSIZE]; for (int i = 0; i < FD_SETSIZE; ++i) { lCliSocketArr[i] = -1; } int lMaxFD = lListenFD; int lMaxClientSocketIndex = -1; fd_set lAllSet; fd_set lReadySet; FD_ZERO(lAllSet); FD_SET(lListenFD, lAllSet); struct timeval tv = {1, 0}; fd_set fdread; char szMessage[MSGSIZE]; FD_ZERO(fdread); while (TRUE) { lReadySet = lAllSet; SOCKET lClient = select(lListenFD,lReadySet,NULL,NULL,&tv); if (FD_ISSET(lListenFD, lReadySet)) { int lAddrSize = sizeof(client); lClientSocket = accept(lMaxFD+1, (sockaddr*)&client, &lAddrSize); printf("Accepted client:%s:%d ", inet_ntoa(client.sin_addr), ntohs(client.sin_port)); // Add socket to g_CliSocketArr for (int i =0 ; i < FD_SETSIZE; ++i) { if (lCliSocketArr[i] < 0) { lCliSocketArr[i] = lClientSocket; break; } } if (i == FD_SETSIZE) { printf("too many client/n"); } if (lClientSocket > lMaxFD) { lMaxFD = lClientSocket; } } int ret = select(0, &fdread, NULL, NULL, &tv);//检测是否有数据可读 if (ret == 0) { // Time expired continue; } for (i = 0; i < g_iTotalConn; i++) { memset(szMessage,0,MSGSIZE); if (FD_ISSET(g_CliSocketArr[i], &fdread)) { // A read event happened on g_CliSocketArr ret = recv(g_CliSocketArr[i], szMessage, MSGSIZE, 0); if (ret == 0 || (ret == SOCKET_ERROR && WSAGetLastError() == WSAECONNRESET)) {//处理发生错误的时候 // Client socket closed printf("Client socket %d closed. ", g_CliSocketArr); closesocket(g_CliSocketArr[i]); if (i < g_iTotalConn - 1) { g_CliSocketArr[i--] = g_CliSocketArr[--g_iTotalConn]; } } else { szMessage[ret] = '