title: How to solve connection reset error while reading/writing from socket in c++
body: <p>My client and server are sending buffer messages to each other. Following is the client side and server side section of read/write code:</p>
  
  <p>Client side:</p>
  
  <pre><code>if (connect( sockfd, (struct sockaddr *) &amp;serv_addr, sizeof(serv_addr) ) &lt; 0) 
  {
      perror("ERROR connecting");
      return(1);
  }    
  
  printf("Recieving Buffer 1 from Server side"); 
  
  bzero(buffer1,256);
  int i = 0;
  
  while (i &lt; 5)
  {
      n = read(sockfd,buffer1,sizeof(buffer1));
      if (n&lt;0)
          printf("ERROR reading in socket %d  len %d", n, sizeof(buffer1));
  
      n = write(sockfd,buff2,sizeof(buff2));
      if(n&lt;0)
          printf("ERROR writing in socket %d  len %d", n, sizeof(buff2));
  
      printf("\nSent Buffer2 (WON'T TERMINAL TYPE) from client side");
  
      i++;
  
  }
  </code></pre>
  
  <p>Server Side :</p>
  
  <pre><code>printf("Server Sending (DO TERMINAL TYPE)\n");
  
  while(1)
  {
      while ((n = write(newsockfd,buff1,sizeof(buff1)))&gt;0)
      {
          printf("Server Sent query %d: %hhX %hhX %hhX\n",count,buff1[count][0],buff1[count][1],                   buff1[count][2]);
          n = read(newsockfd, recbuf , sizeof(recbuf));
          printf("Server received response: %hhX %hhX %hhX\n",recbuf[0],recbuf[1],recbuf[2]);
          count++;
          count = count % 3;
       }
           if (n&lt;0)
          {
              perror("Error writing to socket ");
              exit(1);
          }
  }
  </code></pre>
  
  <p>Output I received :
  server :</p>
  
  <pre><code>./server 9998
  Server Sending (DO TERMINAL TYPE)
  Server Sent query 1: FF FD 1E
  Server received response: FF FC 18
  Server Sent query 2: FF FD 1D
  Server received response: FF FC 18
  Server Sent query 0: FF FD 18
  Server received response: FF FC 18
  Server Sent query 1: FF FD 1E
  Server received response: FF FC 18
  Server Sent query 2: FF FD 1D
  Server received response: FF FC 18
  Server Sent query 0: FF FD 18
  Server received response: FF FC 18
  Error writing to socket : Connection reset by peer
  </code></pre>
  
  <p>client side :</p>
  
  <pre><code>./client 127.0.0.1 9998
  Recieving Buffer 1 from Server side
  Sent Buffer2 (WON'T TERMINAL TYPE) from client side
  Sent Buffer2 (WON'T TERMINAL TYPE) from client side
  Sent Buffer2 (WON'T TERMINAL TYPE) from client side
  Sent Buffer2 (WON'T TERMINAL TYPE) from client side
  Sent Buffer2 (WON'T TERMINAL TYPE) from client side
  </code></pre>
  
  <p>I would like to close the connection after i = 5 that is after 5 buffer messages are exchanged between server-client, but the program gives error of Connection reset by peer (i guess some error from client side). How should I fix this? Thanks in advance</p>