title: Socket client in C fputs
body: <p>I have the following client code that connects to a server: </p>
  
  <pre><code>#include&lt;stdio.h&gt; //printf
  #include&lt;string.h&gt;    //strlen
  #include&lt;sys/socket.h&gt;    //socket
  #include&lt;arpa/inet.h&gt; //inet_addr
  
  int main(int argc , char *argv[])
  {
      int sock;
      struct sockaddr_in server;
      char message[1024], server_reply[2000];
  
      //Create socket
      sock = socket(AF_INET , SOCK_STREAM , 0);
      if (sock == -1)
      {
          printf("Could not create socket");
      }
      puts("Socket created");
  
      server.sin_addr.s_addr = inet_addr("127.0.0.1");
      server.sin_family = AF_INET;
      server.sin_port = htons( 8888 );
  
      //Connect to remote server
      if (connect(sock , (struct sockaddr *)&amp;server , sizeof(server)) &lt; 0)
      {
          perror("connect failed. Error");
          return 1;
      }
  
      puts("Connected\n");
      puts("Bienvenido al Chatroom, puedes empezar a escribir en la sala!");
  
      //keep communicating with server
      while(1)
      {
  
          printf("Enter message: ");
      fgets(message, 1024 ,stdin);
          //scanf("%s" , message);
  
          //Send some data
          if( send(sock , message , 1024 , 0) &lt; 0)
          {
              puts("Send failed");
              return 1;
          }
  
          //Receive a reply from the server
          if( recv(sock , server_reply ,2000, 0) &lt; 0)
          {
              puts("recv failed");
              break;
          }
  
      puts(server_reply);
  
  
      }
  
      close(sock);
      return 0;
  }
  </code></pre>
  
  <p>Whenever I send a message through the socket, the server echoes the message back to the client. It works most of the times, but after a few messages iterations, the echo starts to fail. Here's an example of how it fails.</p>
  
  <blockquote>
    <p>Enter Message: Hi there! Server reply: Hi there!</p>
    
    <p>Enter Message: Where are you from? Server reply: Where are you from?</p>
    
    <p>Enter Message: Nice! Server Reply: Nice! are you from?</p>
    
    <p>Enter Message: And you ? Server Replay: And you ? you from?</p>
    
    <hr>
  </blockquote>
  
  <p>So it seems somehow i keep garbage in the stdout buffer or something like that. I don't really know what it is. Is there anything wrong with the code or just a simple fix up to do with fputs ? (Maybe it has something to do with message and server_reply array's size).</p>