2

I have this UDP Client-Server chat, a small program that I made for a university course, everything runs just fine. But the professor asked me what would happen if a user crashed while sending a message, the server will keep waiting to receive the message from the client that does not exist anymore, so will wait forever. I tried to think of a solution but couldn't find one and really hope someone can help me.

I will leave just the snippet of code that causes the issue. If needed I can provide more or even the full repo.

void Forward_message(int sockfd, ListHead* head, struct sockaddr_in cliaddr){
    Message msg = {0}; 
    int len = sizeof(cliaddr);
    
    if(head->size >1){
        int read_bytes;
        do{
            read_bytes = 0;
            read_bytes = recvfrom(sockfd,(Message *)&msg, sizeof(Message),MSG_WAITALL,(struct sockaddr* )&cliaddr, &len );
            if(read_bytes == -1)perror("An error occurred while receiving Message from the Client"),exit(1);
        }while( (read_bytes != sizeof(Message))  );
        
        Send_msg(&msg,sockfd,head);
        printf("\nmessage forwarded\n");
    
    } 
}

The issue is caused by the recvfrom inside the do while.

Laurel
  • 5,965
  • 14
  • 31
  • 57
  • This topic involved Python, but the solutions are the same for C: https://stackoverflow.com/questions/2719017/how-to-set-timeout-on-pythons-socket-recv-method – mzimmers Jan 13 '22 at 17:03
  • You can choose 1 of 3 things 1.use select or poll or some other variant, and first check if there is anything to read and only then try to read with using recvfrom. select has argument for timeout, so if there is nothing to read for more than specified time it returns. It also return when socket is corectly closed from client 2.set timeout for socket itself with setsockopt, that recvfrom will fail after configured time 3.set socket as non blocking it would return immediately even if there is no message. Probably not usefull for this case. Sorry, don't have time right now for full answer. – Tundy Jan 13 '22 at 17:07
  • Thanks both of you I will try your suggestions – Antonio Ciprani Jan 13 '22 at 17:28

0 Answers0