Reconnecting using socket in c

im using socket in c and succeeding in send / recv. however, the problem is that when my server fails, the client must reconnect to the server (the server starts after a while). so here is what i did:

  • create socket
  • connecting
  • RECV / send
    • if recv size == 0 go to step 2.

this algorithm does not work for me. are there any ideas?

the code:

int initSocket(char *servIP, unsigned short serverPort)
{
    portNum = serverPort;
    ipAddr = servIP;
                            /* Socket descriptor */
    struct sockaddr_in echoServAddr; /* Echo server address */

    if ((sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
    {
        printf("socket() failed");
        bConnected = -1;
        return -1;
    }

    /* Construct the server address structure */
    memset(&echoServAddr, 0, sizeof(echoServAddr));     /* Zero out structure */
    echoServAddr.sin_family      = AF_INET;             /* Internet address family */
    echoServAddr.sin_addr.s_addr = inet_addr(ipAddr);   /* Server IP address */
    echoServAddr.sin_port        = htons(portNum);      /* Server port */

    struct timeval timeout;
    timeout.tv_sec = 0;
    timeout.tv_usec = 20000;

    if (setsockopt (sock, SOL_SOCKET, SO_RCVTIMEO, (char *)&timeout, sizeof(timeout)) < 0)
        error("setsockopt failed\n");

    /*if (setsockopt (sock, SOL_SOCKET, SO_SNDTIMEO, (char *)&timeout, sizeof(timeout)) < 0)
         error("setsockopt failed\n");
    */
    /* Establish the connection to the echo server */
    if (connect(sock, (struct sockaddr *) &echoServAddr, sizeof(echoServAddr)) < 0)
    {
        printf("connect() failed\n");
        bConnected = -1;
        //close(sock);
        return -1;
    }

    bConnected = 0;
    return 0;
}




--------------- if server crashes ------------
if(recv_size == 0)
            {
            // server crashed
                while(initSocket(ipAddr, portNum) < 0)
                {
                    printf("IP : %s\v", ipAddr);
                    printf("Port : %d\v", portNum);                 
                }

            } 
-----------------------------
+3
source share
1 answer
  • create socket
  • connecting
  • recv / send if recv size == 0 go to step 2.

You cannot reconnect a TCP socket, you need to create a new one. You would also like to handle the case when recv or send errors.

So this should be:

  • create socket
  • connecting
  • RECV/ recv <= 0 send -1 ( ): , 1

, , , 2 3, , , .

, initSocket() () , connect() , , () , , .

+5

All Articles