[問題] socket接受multi client的問題
if ( (sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1 ){
perror("socket");
exit(1);
}
addr.sin_family = AF_INET;
addr.sin_port = htons(5000);
addr.sin_addr.s_addr = htonl(INADDR_ANY);
bzero( &(addr.sin_zero), 8 );
if ( bind(sockfd, (struct sockaddr*)&addr, sizeof(struct sockaddr))
== -1 ){
perror("bind");
exit(1);
}
while(1){
if ( listen(sockfd, 10) == -1 ){
perror("listen");
exit(1);
}
if ( (new_fd[num] = accept(sockfd, (struct sockaddr*)
&their_addr, &sin_size)) == -1 ){
perror("accept");
exit(1);
}
res = pthread_create( &(accept_thread[times]), NULL,
thread_function, (void *)p_num );
if (res != 0){
perror("Thread create failed!n");
exit(EXIT_FAILURE);
}
num++;
times++;
}
close(sockfd);
return 0;
}
以上是server片段程式
我想實作一個就是可以接受多個client的socket
以上的code可以做到接收多個client但無法同時執行pthread_create
就是說當我第一個client連線到server時,正執行pthread的thread_function時
當有其他client連入,必須等到pthread結束..等下個accept後才能執行
但我想做到的是
當第一個client連線執行時,這時有另一個client連入後可以馬上接受accept並執行
pthread的thread_function
不知道要如何修改才能達到?
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 175.98.141.254
※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1481854942.A.B04.html
→
12/16 10:53, , 1F
12/16 10:53, 1F
→
12/16 10:59, , 2F
12/16 10:59, 2F
→
12/16 11:00, , 3F
12/16 11:00, 3F
→
12/16 11:00, , 4F
12/16 11:00, 4F
→
12/16 11:01, , 5F
12/16 11:01, 5F
→
12/16 14:08, , 6F
12/16 14:08, 6F
→
12/16 14:08, , 7F
12/16 14:08, 7F
→
12/16 14:09, , 8F
12/16 14:09, 8F
推
12/19 08:42, , 9F
12/19 08:42, 9F
→
12/19 08:42, , 10F
12/19 08:42, 10F
→
12/19 08:44, , 11F
12/19 08:44, 11F
→
12/19 08:44, , 12F
12/19 08:44, 12F
→
12/19 18:19, , 13F
12/19 18:19, 13F
→
12/19 18:19, , 14F
12/19 18:19, 14F
→
12/20 15:23, , 15F
12/20 15:23, 15F
討論串 (同標題文章)
以下文章回應了本文:
完整討論串 (本文為第 1 之 2 篇):