Lasitha Yapa
Lasitha Yapa

Reputation: 4609

Reconnection does not work as expected

I am using sys/socket.h for sending heartbeats to a server repeatedly.
Connection work fine. Problem occurs when server restart.
This is my code.

bool HbClient::start(const char *address, int port)
{
   //create socket if it is not already created
   if(sock == -1)
   {
      sock = socket(AF_INET , SOCK_STREAM , 0);
      if (sock == -1)
      {
         printf("Could not create socket object");
         return false;
      }

      printf("Socket object created\n");
   }

   server.sin_addr.s_addr = inet_addr( address );
   server.sin_family = AF_INET;
   server.sin_port = htons( port );

   return connect_to_server();
}

bool HbClient::connect_to_server()
{
   int status = connect(sock , (struct sockaddr *)&server , sizeof(server));

   cout << "returned status: " << status << endl << flush;
   if (status < 0)
   {
      cout << "Error. Connection failed." << endl << flush;
      return false;
   }

   cout << "Connected to server" << endl << flush;
   return true;
}

bool HbClient::send_data(const char *data)
{
   int res = send(sock , data , strlen(data) , MSG_NOSIGNAL);
   if( res < 0)
   {
      cout << "Data sending failed, status: " << res << endl << flush;
      start("127.0.0.1", 9090);
      return false;
   }
   cout << "Data send" << endl << flush;

   return true;
}

send_data() function is invoked repeatedly. Until server restart this works fine. But when server restart these outputs were printed repeatedly.

Data sending failed, status: -1
returned status: -1
Error. Connection failed.

I am using Ubuntu 16.04 OS and g++ compiler. Can you point out what the issue here?

Upvotes: 0

Views: 30

Answers (1)

pure cuteness
pure cuteness

Reputation: 1635

Close socket and set it to -1 before reconnecting. So modify your send_data function like this:

close(sock);
sock = -1;
start("127.0.0.1", 9090);

Also socket function always return -1 on failure. You should print errno instead of returned code

Upvotes: 1

Related Questions