I am trying to make a server which can send data to more than one client for which as a client is connected it creates a thread which continuously send data to client as it recieves some control info from client side.To stop transmission server receives another control request from client ,to receive request to stop there is another thread created by data sending thread.
For single client my code is working finely but for more than one client it only send data to newly arrived client.
Can you suggest me some idea to make it work.
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
Since you don’t show all the code, I have to guess… And my guess is that it’s because you only have one
ta1in themainfunction. It is a pointer to some structure, and you send the pointer to the thread. But since there is only one pointer, that you send to both threads, then the variabletain both threads point to the same structure. So when the second connection is made, the information for the first thread is overwritten with the information for the second.To solve this, you need to make an array, like the
connectedarray.