1 #include <iostream> 2 #include <WinSock2.h> 3 4 using namespace std; 5 6 #pragma comment(lib, "ws2_32") 7 8 int main(int argc, char **argv) 9 { 10 WSADATA wsaData; 11 WSAStartup(WINSOCK_VERSION, &wsaData); 12 13 USHORT uPort = 4567; 14 SOCKET sListen = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); 15 if (INVALID_SOCKET == sListen) 16 { 17 cout << "socket error : " << GetLastError() << endl; 18 return 0; 19 } 20 21 SOCKADDR_IN sin; 22 sin.sin_family = AF_INET; 23 sin.sin_port = htons(uPort); 24 sin.sin_addr.S_un.S_addr = INADDR_ANY; 25 26 if (SOCKET_ERROR == bind(sListen, (PSOCKADDR)&sin, sizeof(sin))) 27 { 28 cout << "Bind error : " << WSAGetLastError() << endl; 29 closesocket(sListen); 30 WSACleanup(); 31 return 0; 32 } 33 34 if (SOCKET_ERROR == listen(sListen, 5)) 35 { 36 cout << "listen error : " << WSAGetLastError() << endl; 37 closesocket(sListen); 38 WSACleanup(); 39 return 0; 40 } 41 42 fd_set fdSocket; 43 FD_ZERO(&fdSocket); 44 FD_SET(sListen, &fdSocket); 45 46 while (TRUE) 47 { 48 fd_set fdRead = fdSocket; 49 int iRet = select(0, &fdRead, NULL, NULL, NULL); 50 if (iRet > 0) 51 { 52 for (size_t i = 0; i < fdSocket.fd_count; i++) 53 { 54 if (FD_ISSET(fdSocket.fd_array[i], &fdRead)) 55 { 56 if (fdSocket.fd_array[i] == sListen) 57 { 58 if (fdSocket.fd_count < FD_SETSIZE) 59 { 60 SOCKADDR_IN addrRemote; 61 int iAddrLen = sizeof(addrRemote); 62 SOCKET sNew = accept(sListen, (PSOCKADDR)&addrRemote, &iAddrLen); 63 FD_SET(sNew, &fdSocket); 64 cout << "接收到连接(" << inet_ntoa(addrRemote.sin_addr) << ")" << endl; 65 } 66 else 67 { 68 cout << "连接太多!" << endl; 69 continue; 70 } 71 } 72 else 73 { 74 char szText[256]; 75 int iRecv = recv(fdSocket.fd_array[i], szText, strlen(szText), 0); 76 if (iRecv > 0) 77 { 78 szText[iRecv] = '