// select.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include <WinSock2.h> #include <Windows.h> #include <iostream> #pragma comment(lib,"ws2_32.lib") int _tmain(int argc, _TCHAR* argv[]) { WORD wVersion = MAKEWORD(2,2); WSADATA wsaData = {0}; if(WSAStartup(wVersion,&wsaData)!=0) { printf("Inin WSAStartup Error\r\n"); return -1; } SOCKET ListenSocket = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP); if(ListenSocket==INVALID_SOCKET) { WSACleanup(); printf("Create Socket Error\r\n"); return -1; } sockaddr_in LocalAddress; LocalAddress.sin_family = AF_INET; LocalAddress.sin_port = htons(9627); LocalAddress.sin_addr.S_un.S_addr = INADDR_ANY; if(bind(ListenSocket,(sockaddr*)&LocalAddress,sizeof(LocalAddress))==SOCKET_ERROR) { closesocket(ListenSocket); WSACleanup(); printf("Failed bind()\r\n"); return -1; } listen(ListenSocket,5); fd_set fdSocket; FD_ZERO(&fdSocket); FD_SET(ListenSocket,&fdSocket); while(true) { fd_set fdRead = fdSocket; int iPending = select(0,&fdRead,NULL,NULL,NULL); if(iPending>0) { for(int i=0;i<(int)fdSocket.fd_count;i++) { if(FD_ISSET(fdSocket.fd_array[i],&fdRead)) { if(fdSocket.fd_array[i]==ListenSocket) //什么时候不相等,即能跳到下一个else { if(fdSocket.fd_count<FD_SETSIZE) { sockaddr_in addrRemote; int nAddrLen = sizeof(addrRemote); SOCKET sNew = accept(ListenSocket,(sockaddr*)&addrRemote,&nAddrLen); FD_SET(ListenSocket,&fdSocket); printf("接收到链接:%s\n",inet_ntoa(addrRemote.sin_addr)); } else { printf("Too much connections!\n"); continue; } } else { char szBufferData[0x1000]; int iReturn = recv(fdSocket.fd_array[i],szBufferData,0x1000,0); if(iReturn > 0) { szBufferData[iReturn] = ‘\0‘; printf("接受信息:%s\n", szBufferData); } else { closesocket(fdSocket.fd_array[i]); FD_CLR(fdSocket.fd_array[i],&fdSocket); } } } } } } return 0; }
时间: 2024-10-20 11:02:11