Reputation: 706
so i would like to connect several clients to server with socket under linux kernel 2.6.x. when a client is connected,the server will send a welcome message to the client,in a manner of displaying on the standard output or anything.so when the connection is on,one thread is given to a function that may deliver welcome message to the very client.when i was using another processor to accomplish this job,it is just fine.however,when i switched to pthread way,the clients could not get anything from the server.at this point,i checked netstat,the connection was still on.so there comes my code:
client.c
// to make long story short,
// i'll just omit most of declarations and stuff that is irrelavent to the problem
#define PORT 12345
#define IP_ADDR "127.0.0.1"
void *process_to_server(int socket);
int main(){
// i'll skip building socket for your convinence
process_to_server(socket_server);
}
void *process_to_server(int socket){
ssize_t size=0;
char buffer[1024];
size=read(socket,buffer,1024);
write(1,buffer,size+1);// output the welcome message to the client's standard output
}
server.c
#define PORT 12345
void *process_to_client(int socket);
int main(){
// same spirit as above
while(1){
int addrlen=sizeof(struct sockaddr);
socket_client = accept(socket_server,(struct sockaddr*)&client_addr,&addrlen);
if(socket_client<0) continue;
pthread_t pth;
close(socket_server);
pthread_create(&pth,NULL,(void*)&process_to_client,&socket_client);
}
}
void *process_to_client(int socket){
char buffer[1024];
sprintf(buffer,"Hello There\n");
write(socket,buffer,1024);
}
Upvotes: 2
Views: 7868
Reputation: 2791
You are transferring &socket_client
to worker thread, but using the thread function parameter as if it was socket_client
You can do this:
int main() {
/*...*/
pthread_create(&pth,NULL,(void*)&process_to_client,(void*)socket_client);
/*...*/
}
void *process_to_client(void* pvsocket) {
int socket = (int) pvsocket;
/* same as before */
}
Also closing the listening socket will keep the accepted connection open. You will be able to continue communication with connected client but further incoming connection will not be accepted. The worker thread should close socket_client
when communication is done.
Upvotes: 1
Reputation: 409356
The argument to your thread function is a pointer, but you use it directly as an integer. Change your thread function like this:
void *process_to_client(void *socket_pointer){
int socket = *(int *) socket_pointer;
char buffer[1024];
sprintf(buffer,"Hello There\n");
write(socket,buffer,1024);
}
Upvotes: 1