Disconnecting from server

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • tawanda diza
    New Member
    • Sep 2011
    • 29

    Disconnecting from server

    Hie Team.

    I am having this problem:
    I am developing an application that is connecting to a server, the problem is when the server is not responding, the application wont allow me to do anything so i end up restarting the machine,

    i am receiving data using the receive function as follows
    Code:
    nData = recv( hServer, &wzRec[iPos], nLeft, 0 );
    please help

    thanks in advance
  • johny10151981
    Top Contributor
    • Jan 2010
    • 1059

    #2
    I search on google about your problem.

    I got one commmon solution it says using select() function before using receive

    another solution i got a forum is more interesting
    Code:
       { /* this block is just after the return from the socket() call and before connect() */
                struct timeval tv; /* timeval and timeout stuff added by davekw7x */
                int timeouts = 0;
                tv.tv_sec = 3;
                tv.tv_usec = 0;
                if (setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, (char *)&tv,  sizeof tv))
                {
                  perror("setsockopt");
                  return -1;
                }
    
                if (connect(sockfd, (struct sockaddr *)&their_addr, sizeof their_addr) == -1) {
                    perror("connect");
                    exit(1);
                }
    
                while (((numbytes=recv(sockfd, buf, MAXDATASIZE-1, 0)) == -1) && (++timeouts < 1000)) { /* loop to retry in case it timed out; added by davekw7x */
                    perror("recv");
                    printf("After timeout #%d, trying again:\n", timeouts);
                }
                printf("numbytes = %d\n", numbytes);
    
                buf[numbytes] = '\0';
    
                printf("Received: %s",buf);
            }
    if you want to see the entire thread follow the link

    Comment

    • tawanda diza
      New Member
      • Sep 2011
      • 29

      #3
      hie johny

      do yu have any idea on how to use this code for that problem above
      Code:
      struct timeval tv;
      
        tv.tv_sec = 3;  // 1 Secs Timeout 
      
        setsockopt(hServer, SOL_SOCKET, SO_RCVTIMEO,(char*)&tv,sizeof(struct timeval));
      I would be very grateful if you would tel me where exactly to put the code like what you told me in your first reply

      I am having problems with your first code its not doing any thing at the moment.
      THANKS
      Last edited by tawanda diza; Oct 21 '11, 09:38 AM. Reason: No clear clafication.

      Comment

      Working...