- 相關(guān)推薦
C語言socket多線程編程限制客戶端連接數(shù)
C語言傳遞參數(shù)均是以值傳遞(pass by value),另外也可以傳遞指針(a pointer passed by value)。以下是小編為大家搜索整理的C語言socket多線程編程限制客戶端連接數(shù),希望能給大家?guī)韼椭?更多精彩內(nèi)容請及時關(guān)注我們應(yīng)屆畢業(yè)生考試網(wǎng)!
先上一些多線程需要使用的函數(shù)定義:
代碼如下:
DWORD WINAPI ProcessClientRequests(LPVOID lpParam) //新線程將會執(zhí)行的函數(shù)定義
{
return 0;
}
HANDLE handler=CreateThread(NULL, 0, ProcessClientRequests, &clientsocket, 0, NULL); //這里比較簡單,&clientsocket是個指針,是從主線程傳入新線程的參數(shù)
WaitForMultipleObjects(MAXCLIENTS, threads, TRUE, INFINITE); //用來阻塞主線程,直到所有創(chuàng)建的子線程都完成任務(wù)為止,才繼續(xù)執(zhí)行后面的代碼
for(int i=0;i
{
CloseHandle(threads[i]); //創(chuàng)建的每個子線程的HANDLE都會被保存在HANDLE數(shù)組中,這個函數(shù)用于關(guān)閉各個handle所對應(yīng)的線程空間
}
服務(wù)器端程序
主線程代碼如下:
代碼如下:
#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!rn";
send(clientsocket, msg, strlen(msg)+sizeof(char), NULL); //發(fā)送拒絕連接消息給客戶端
printf("***SYS*** REFUSED.n");
closesocket(clientsocket); //釋放資源
break;
}
}
printf("Maximize clients occurred for d%.rn", MAXCLIENTS);
WaitForMultipleObjects(MAXCLIENTS, threads, TRUE, INFINITE); //等待所有子線程,直到完成為止
closesocket(s);
for(int i=0;i
{
CloseHandle(threads[i]); //清理線程資源
}
WSACleanup();
printf("Cleared all.rn");
getchar();
exit(0);
}
子線程函數(shù)定義
代碼如下:
DWORD WINAPI ProcessClientRequests(LPVOID lpParam)
{
SOCKET* clientsocket=(SOCKET*)lpParam; //這里需要強(qiáng)制轉(zhuǎn)換,注意:指針類型的
char* msg="Hello, my client.rn";
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.rn";
send(*clientsocket, msg_bye, strlen(msg_bye)+sizeof(char), NULL);
break;
}
printf("***Client*** %sn", buffer);
}
closesocket(*clientsocket);
return 0;
}
【C語言socket多線程編程限制客戶端連接數(shù)】相關(guān)文章:
C語言socket編程使用方法06-20
C語言socket編程使用方法簡介07-29
C語言編程基礎(chǔ)08-17
C語言入門什么是編程語言10-12
如何學(xué)習(xí)C語言編程10-28
C語言設(shè)置和取得socket狀態(tài)的相關(guān)函數(shù)用法介紹10-13
講解Java的Socket網(wǎng)絡(luò)編程的多播與廣播實現(xiàn)09-03
C語言編程常犯錯誤小結(jié)10-11