#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#define maxline 1000
#define listenq 20
#define port 5000
#define maxfd 20
#define backlog 3
#define maxdatasize 1024
typedef struct _client
client;
//最大客戶端數
static int maxi=0;
//socketid
int sockfd;
//客戶端列表
client *clients;
//客戶端連線線程
pthread_t accthread;
//初始化鍊錶
void init(client **c)
//獲取客戶端數量
int getsize(client *c)
return count;
}//通過客戶端id獲取客戶端
client* getclient(client *c,int d)
return null;
}//新增客戶端
void add(client **c,int d)
//刪除指定的客戶端
void removeclient(int d)
//關閉所有客戶端
void closeclients()
}//向客戶端廣播訊息
void sendall(char *msg)
c = p;}}
//接收訊息
void recvmessage(void *new_fd)
if(numbytes == 0)
if(strcmp(buf,"exit")==0)
printf("recv from client %d: %s\n",fd,buf);
//todo:如果需要向客戶端回碼,去掉下面的注釋
//if(write(fd,send_data,strlen(send_data)) == -1)//}
pthread_exit(null);
}//客戶端連線
void acceptconnect()
sin_size = sizeof(struct sockaddr_in);
if((new_fd = accept(sockfd,(struct sockaddr*)&thier_addr,&sin_size)) == -1)
printf("客戶端%d上線\n",new_fd);
add(&clients,new_fd);
pthread_t thread_id;
if(pthread_create(&thread_id,null,(void *)(&recvmessage),(void *)&new_fd) == -1)
}pthread_exit(null);
}int main()
my_addr.sin_family = af_inet;
my_addr.sin_port = htons(port);
my_addr.sin_addr.s_addr = inaddr_any;
bzero(&(my_addr.sin_zero),8);
if(bind(sockfd,(struct sockaddr*)&my_addr,sizeof(struct sockaddr)) == -1)
printf("伺服器監聽埠%d\n",port);
if(listen(sockfd,backlog) == -1)
printf("服務啟動\n");
init(&clients);
if((pthread_create(&accthread,null,(void*)acceptconnect,null)) !=0)
while(1)}}
Socket 多執行緒
服務端 include include pragma comment lib,ws2 32 include void sendfuction socket sockconn void recvfunction socket sockclient void main if lobyte wsadata...
C語言多執行緒
首先多執行緒需要乙個標頭檔案進行導包 include 接下來我們需要弄乙個執行緒變數,建立到 都可以,不過推薦建立到外邊,比如pthread t th1 接下來我們開始建立執行緒,如果是大型工程的話,建議放到乙個函式裡邊,這個語句是pthread create th1,null,awm,null 如...
C語言多執行緒
pthread create的含義為 intpthread create pthread t tidp,constpthread attr t attr,void start rtn void void arg pthread ttidp為指向執行緒識別符號的指標。constpthread attr...