0
我想做一個服務器,可以發送數據到多個客戶端作爲客戶端連接它創建一個線程連續發送數據到客戶端,因爲它接收一些控制信息來自客戶端。要停止傳輸服務器接收到來自客戶端的另一個控制請求,要接收請求停止,則會有另一個由數據發送線程創建的線程。 對於單個客戶端,我的代碼工作得很好,但對於多個客戶端,它只將數據發送到新到客戶端。 你能否建議我一些想法讓它工作。多線程服務器爲多個客戶端
for(i=0;i<N;i++){ // main accept() loop
sin_size = sizeof client_addr;
connected[i] = accept(sock, (struct sockaddr *)&client_addr, &sin_size);
if (connected[i] == -1) {
perror("accept");
continue;
}
inet_ntop(client_addr.ss_family,get_in_addr((struct sockaddr *)&client_addr),s1[i], sizeof s1[i]);
printf("server: got connection from %s\n%d waiting for data request from client:.......\n", s1[i],connected[i]);
fflush(stdout);
ta1->sockid=connected[i];
ta1->count=i;
if(pthread_create(&tid1[i],NULL,service,(void*)ta1)){
fprintf(stderr,"error in creating tid1");
exit(1);
}
}
for(i=0;i<N;i++){
pthread_join(tid1[i],NULL);
}
close(connected[1]);
return 0;
}//end of main
void* service(void* argu)
{
struct thargu *ta=(struct thargu *)argu;
char control;
printf("coming %d\n",ta->sockid);
if(recv(ta->sockid,&control,1,0)==-1)
{perror("error in recv of service");exit(1);}
printf("recv control at %dsockid\n",ta->sockid);
if(pthread_create(&tid2[ta->count],NULL,stoptx,(void*)ta)==-1)
{perror("error in creating tid2");exit(1);}
while(1)
{
if(control=='a')
{
pthread_mutex_lock(&data_lock);
if(send(ta->sockid,&t1,sizeof(struct transfer),0)==-1)
{perror("error in send of service");exit(1);}
control=v;
v='\0';
pthread_mutex_unlock(&data_lock);
printf("data to %d\n",ta->sockid);
fflush(stdout);
sleep(4);
}
if((control=='b') && (ta->count==k))
{k=200; break;}
control='a';
}//end of while
printf("\ncoming\n");
pthread_join(tid2[ta->count],NULL);
pthread_exit(NULL);
}//end of service
void* stoptx(void* sock)
{
struct thargu *ta=(struct thargu *)sock;
char b;
pthread_mutex_lock(&data_lock2);
if(recv(ta->sockid,&v,1,0)==-1)
{perror("error in recv of stoptx");return 0;}
k=ta->count;
pthread_mutex_unlock(&data_lock2);
printf("inside stoptx %d\n",ta->sockid);
pthread_exit(NULL);
}//end of stoptx