Hey everyone,
I have a client program that is supposed to send the server two numbers and the server is supposed to return the sum of those numbers. The server has to be multi-threaded because in th context of my project, any number of clients can connect at once. Basically whats happening is if I connect 3 clients to the server, only the last one gets results, and im not really sure why. I've been working on it for a few hours and I can't seem to find the error.
anyway here is the loop where I spawn my threads:
Code:
while (1)
{
/* accept a connection from a client program */
int newFD;
pthread_t tid;
newFD = accept( socketFD, (struct sockaddr *)&srcAddr, (socklen_t *)&fromlen );
if ( newFD < 0 )
{
perror( "NATbox:accept()" );
return -1;
}
int threadError = pthread_create(&tid, NULL, respond, (void *) newFD);
if(threadError < 0)
{
perror("NATbox:spawn thread\n");
return -1;
}
}
int status;
int i = 0;
while( i != -1 )
{
i = wait( &status );
printf( "Finished pid = %d\n", i );
}
And here is the function that each thread calls:
Code:
/**
* function that responds to client requests
* adds two numbers received from the client
* then returns the result
*/
void * respond( void * incomingRequestFD )
{
int buffer[2];
int retVal = 1;
int value;
char response[3];
//copy socket
int newFD = *(int * ) incomingRequestFD;
printf("socket: %d\n", newFD);
/* receive data from the sender */
while(retVal != 0 )
{
retVal = recv(newFD, buffer, sizeof(buffer), 0);
if(retVal < 0)
{
perror("add_server:recv()");
exit(1);
}
printf("received: %d\t%d\n", buffer[0], buffer[1]);
/* add the two received numbers together */
value = buffer[0] + buffer[1];
printf("value: %d\n", value);
/* write the int to the buffer */
sprintf(response, "%d", value);
/* send result to client */
send(newFD, response, sizeof(response), 0);
}
/* close socket */
close(newFD);
return 0;
}/* end respond */
Thanks,
Hunter