簡單的多執行緒的TCP伺服器程式碼
阿新 • • 發佈:2019-02-12
#include <stdio.h> #include <sys/types.h> #include <sys/socket.h> #include <time.h> #include <string.h> #include <unistd.h> #include <stdlib.h> #include <pthread.h> #include <arpa/inet.h> #define CLIENTNUM 5 #define BACKLOG 5 #define BUFFLEN 30 pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER; static void *handle_request(void *argv) { int s_s = *((int *)argv); int s_c; struct sockaddr_in from; socklen_t len = sizeof(s_s); for(;;) { time_t now; char buf[BUFFLEN]; int n = 0; pthread_mutex_lock(&m); //上鎖 s_c = accept(s_s,(struct sockaddr *)&from,&len); memset(buf,0,BUFFLEN); n = recv(s_c,buf,BUFFLEN,0); if(n >0) { memset(buf,0,BUFFLEN); now = time(NULL); sprintf(buf,"%24s\r\n",ctime(&now)); send(s_c,buf,strlen(buf),0); } close(s_c);//關閉客戶端 pthread_mutex_unlock(&m); } return NULL; } static void handle_connect(int s) { int s_s = s; pthread_t thread[CLIENTNUM]; int i = 0; for(i;i<CLIENTNUM;i++) { //建立執行緒 pthread_create(&thread[i],NULL,handle_request,(void *)&s_s); } for(i=0;i<CLIENTNUM;i++) { pthread_join(thread[i],NULL); //等待執行緒結束 } } int main(int argc, char *argv[]) { int s_s ;//伺服器套接字檔案描述符 struct sockaddr_in local; s_s = socket(AF_INET,SOCK_STREAM,0); if(s_s <0) { perror("socket()"); exit(1); } memset(&local,0,sizeof(local)); local.sin_family = AF_INET; local.sin_port = htonl(10000); inet_pton(AF_INET,"0.0.0.0",(struct sockaddr*)&local); bind(s_s,(struct sockaddr *)&local,sizeof(local)); //繫結 listen(s_s,BACKLOG); //監聽 //處理客戶端連結 handle_connect(s_s); close(s_s); return 0; }