c說話socket多線程編程限制客戶端銜接數。本站提示廣大學習愛好者:(c說話socket多線程編程限制客戶端銜接數)文章只能為提供參考,不一定能成為您想要的結果。以下是c說話socket多線程編程限制客戶端銜接數正文
先上一些多線程須要應用的函數界說:
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所對應的線程空間
}
辦事器端法式
主線程代碼以下:
#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;
}