recvfrom infinite receiving problem
I m writing a server using udp socket. After a client send first message to connect, i open new socket to communicate with this client on this socket (first sockets for listening) and create a thread for each client. But in thread, the while loop goes infinitely because recvfrom receive data everytime altough any client send data. What is the problem in my code?
The code sample below:
int main()
{
.....
// creating socket
if( (sock = socket(AF_INET, SOCK_DGRAM, 0) ) == -1 )
{
perror("Socket cannot be created\n");
return FAILURE;
}
.....
for(; ;)
{
// TAKE CLIENTS INFORMATION
/**************************************/
recvfrom(sock, &client, sizeof(Client), MSG_WAITALL, (struct sockaddr *)&clientAddr, &size); //1
.......
if( (sock2 = socket(AF_INET, SOCK_DGRAM, 0) ) == -1 )
{
perror("Socket cannot be created\n");
return FAILURE;
}
client.sock = sock2;
...
pthread_create(thid+num_client-1, NULL, messanger, (void*)(clients + num_client-1));
} // end of for loop
}// end of main
// thread function
void *messanger(void *argClient)
{
Client client = *(Client*)argClient;
...
while(strcmp(message.buffer, "exit") != 0)
{
r开发者_开发知识库ecvfrom(client.sock, &message, sizeof(Message), MSG_WAITALL, (struct sockaddr *)&clientAddr, &size);
printf("%s\n", message.buffer);
}// this file loops infinetely altough client does not send data. Printf prints onln new line
}
Where do you bind()
the second socket (or the first, for that matter)? Why aren't you checking recvfrom()
for failure?
This isn't the way to write a UDP server, anyway. You use a single socket to recieve all packets. You then inspect the sender address, match it up with the right client and handle it as appropriate (for example, you could put it onto a work queue for a per-client thread, then wake that thread up using pthread_cond_signal()
).
You're busy-waiting. Try using poll or select instead.
精彩评论