-
C Socket初探 - 参加多线程支撑,限制最大接入客户端个数
添加时间:2013-7-29 点击量:先上一些多线程须要应用的函数定义:
DWORD WINAPI ProcessClientRequests(LPVOID lpParam) //新线程将会履行的函数定义
{
return 0;
}
HANDLE handler=CreateThread(NULL, 0, ProcessClientRequests, &clientsocket, 0, NULL); //这里斗劲简单,&clientsocket是个指针,是从主线程传入新线程的参数
WaitForMultipleObjects(MAXCLIENTS, threads, TRUE, INFINITE); //用来梗阻主线程,直到所有创建的子线程都完成任务为止,才持续履行后面的代码
for(int i=0;i<MAXCLIENTS; i++)
{
CloseHandle(threads[i]); //创建的每个子线程的HANDLE都邑被保存在HANDLE数组中,这个函数用于封闭各个handle所对应的线程空间
}
先附上C Socket初探这篇文章的url
开端,客户端法度没有任何批改,是以此处略(请看C Socket初探中代码所示)
办事器端法度
主线程代码如下:
#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<MAXCLIENTS) //断定是否已经超出最大连接数了
{
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<MAXCLIENTS; i++)
{
CloseHandle(threads[i]); //清理线程资料
}
WSACleanup();
printf(Cleared all.\r\n);
getchar();
exit(0);
}子线程函数定义
DWORD WINAPI ProcessClientRequests(LPVOID lpParam)
{
SOCKET clientsocket=(SOCKET)lpParam; //这里须要强迫转换,重视:指针类型的
char msg=Hello, my client.\r\n;
send(clientsocket, msg, strlen(msg)+sizeof(char), NULL);
printf(SYS HELLO.\n);
while(TRUE)
{
char buffer[MAXBYTE]={0};
recv(clientsocket, buffer, MAXBYTE, NULL);
if(strcmp(buffer, exit)==0)
{
char msg_bye=Bye.\r\n;
send(clientsocket, msg_bye, strlen(msg_bye)+sizeof(char), NULL);
break;
}
printf(Client %s\n, buffer);
}
closesocket(clientsocket);
return 0;
}
运行结果图:
读书,不要想着实用,更不要有功利心。读书只为了自身的修养。邂逅一本好书如同邂逅一位知己,邂逅一个完美之人。有时心生敬意,有时怦然心动。仿佛你心底埋藏多年的话,作者替你说了出来,你们在时光深处倾心相遇的一瞬间,情投意合,心旷神怡。