#define MAXCLIENTS 3 //宏定义,最多3个客户端连接
int main()
{
WSADATA wsaData;
WSAStartup(MAKEWORD(2, 2), &wsaData);
HANDLE threads[MAXCLIENTS];
SOCKET s=socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
sockaddr_in sockaddr;
sockaddr.sin_family=PF_INET;
sockaddr.sin_addr.S_un.S_addr=inet_addr("127.0.0.1");
sockaddr.sin_port=htons(9000);
bind(s, (SOCKADDR*)&sockaddr, sizeof(SOCKADDR));
listen(s, 1);
printf("listening on port [%d].\n", 9000);
int existingClientCount=0;
while(TRUE)
{
SOCKADDR clientAddr;
int size=sizeof(SOCKADDR);
SOCKET clientsocket;
clientsocket=accept(s, &clientAddr, &size);
printf("***SYS*** New client touched.\n");
if(existingClientCount
{
threads[existingClientCount++]=CreateThread(NULL, 0, ProcessClientRequests, &clientsocket, 0, NULL); //启动新线程,并且将socket传入
}
else
{
char* msg="Exceeded Max incoming requests, will refused this connect!\r\n";
send(clientsocket, msg, strlen(msg)+sizeof(char), NULL); //发送拒绝连接消息给客户端
printf("***SYS*** REFUSED.\n");
closesocket(clientsocket); //释放资源
break;
}
}
printf("Maximize clients occurred for d%.\r\n", MAXCLIENTS);
WaitForMultipleObjects(MAXCLIENTS, threads, TRUE, INFINITE); //等待所有子线程,直到完成为止
closesocket(s);
for(int i=0;i
{
CloseHandle(threads[i]); //清理线程资源
}
WSACleanup();
printf("Cleared all.\r\n");
getchar();
exit(0);
}