#include<winsock2.h>
#include<stdio.h>
#include<windows.h>
#pragma comment(lib,"WS2_32.lib")
BOOL InsertSock(SOCKET* pSock, SOCKET sock)
{
for (int nIndex = 0; nIndex < FD_SETSIZE - 1; nIndex++)
{
if (pSock[nIndex] == INVALID_SOCKET)
{
pSock[nIndex] = sock;
break;
}
}
if (nIndex == FD_SETSIZE - 1)
return FALSE;
return TRUE;
}
int main(int argc, char* argv[])
{
WSADATA wsaData;
WORD sockVersion=MAKEWORD(2,0);
WSAStartup(sockVersion,&wsaData);
SOCKET clientsockarray[FD_SETSIZE - 1];
SOCKET s=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
if(s==INVALID_SOCKET)
{
printf(" Failed socket()\n");
WSACleanup();
return 0;
}
sockaddr_in sin;
sin.sin_family=AF_INET;
sin.sin_port=htons(8888);
sin.sin_addr.S_un.S_addr=INADDR_ANY;
if(bind(s,(LPSOCKADDR)&sin,sizeof(sin))==SOCKET_ERROR)
{
printf(" Failed bind() %d\n",GetLastError());
WSACleanup();
return 0;
}
if(listen(s,63)==SOCKET_ERROR)
{
printf(" Failed listen()\n");
WSACleanup();
return 0;
}
for (int i=0;i < 64; i++)
{
clientsockarray[i] = INVALID_SOCKET;
}
sockaddr_in remoteAddr;
int nAddrLen=sizeof(remoteAddr);
//char szText[]="Hello World!";
FD_SET fd;
FD_ZERO(&fd);
TIMEVAL tv={30,0};
FD_SET(s,&fd);
printf("server start:%d\n",GetLastError());
int num=0;
while(TRUE)
{
int nResult;
nResult = select(0,&fd, NULL,NULL,&tv);
if (nResult == SOCKET_ERROR)
{
printf("select failed \n");
continue;
}
/*
if (nResult > 0)
{
printf("dddddddddd\n");
}
*/
if(FD_ISSET(s,&fd))
{
SOCKET client;
client=accept(s,(SOCKADDR*)&remoteAddr,&nAddrLen);
if (client == INVALID_SOCKET)
{
printf("client connect fail %d",GetLastError());
continue;
}
if(!InsertSock(clientsockarray,client))
{
printf("³¬¹ý×î´óSOCKET\n");
closesocket(client);
continue;
}
FD_SET(client,&fd);
}
// Öð¸ö´¦Àí´¦ÓÚ´ý¾ö״̬µÄÌ×½Ó×Ö
nResult = select(0,&fd, NULL,NULL,&tv);
if (nResult == SOCKET_ERROR)
{
printf("select failed \n");
continue;
}
for (int nIndex = 0; nIndex <= FD_SETSIZE - 1; nIndex++)
{
if(FD_ISSET(clientsockarray[nIndex], &fd))
{
//printf("aaaa\n");
char buffer[256];
int nRet = recv(clientsockarray[nIndex], buffer, sizeof(buffer), 0);
if (nRet == 0 || nRet == SOCKET_ERROR)
{
closesocket(clientsockarray[nIndex]);
clientsockarray[nIndex] = INVALID_SOCKET;
continue; // ¼ÌÐø´¦ÀíÌ×½Ó×Ö¾ä±úÊý×éÖеÄÆäËüÌ×½Ó×Ö
}
// ½«½ÓÊܵ½µÄÊý¾Ý½øÐд¦Àí,´Ë´¦Ö»½«ÆäÊä³ö
//char buffer[256];
//recv(clientsockarry[nIndex],buffer,256);
printf("has recv data from socket %d : %s",i, buffer);
printf(" num:%d\n",++num);
}
}
}
closesocket(s);
WSACleanup();
return 0;
}