title: Sending multiple messages via send() recv(), Socket programming, C
body: <p>I'm trying to make a program (client) which kan send a message to a server upon request from user. Stripped down code follows:</p>
  
  <p>Client:</p>
  
  <pre><code>int main(int argc, char **argv) {
  
    struct sockaddr_in servaddr;
    int sock = socket(AF_INET, SOCK_STREAM, 0);
  
    memset(&amp;servaddr, 0, sizeof(servaddr));
    servaddr.sin_family = AF_INET;
    servaddr.sin_port = htons(6789);
    servaddr.sin_addr.s_addr = inet_addr(&lt;ip_address_of_server&gt;);
  
    while(1) {
  
      char message[161];
      fgets(message, 161, stdin);
  
      /* Replacing '\n' with '\0' */
      char *tmp = strchr(message, '\n');
      if (tmp) *tmp = '\0';
  
      connect(sock, (struct sockaddr *)&amp;servaddr, sizeof(servaddr));
      send(sock, message, strlen(message), 0);
      close(sock);
    }
  }
  </code></pre>
  
  <p>Server:</p>
  
  <pre><code>int main(int argc, char **argv) {
  
    struct sockaddr_in servaddr;  
    int sock = socket(AF_INET, SOCK_STREAM, 0);
  
    memset(&amp;servaddr, 0, sizeof(servaddr));
    servaddr.sin_family = AF_INET;
    servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
    servaddr.sin_port = htons(6789);
  
    bind(sock, (struct sockaddr *)&amp;servaddr, sizeof(servaddr));  
    listen(sock, 5);
  
    while(1) {
      int clisock = accept(sock, (struct sockaddr *) NULL, NULL);
  
      if (clisock &gt;= 0) {
        int messageLength = 160;
        char message[messageLength+1];
        int in, index = 0, limit = messageLength;
  
        while ((in = recv(clisock, &amp;message[index], messageLength, 0)) &gt; 0) {
          index += in;
          limit -= in;
        }
  
        printf("%s\n", message);
      }
  
      close(clisock);
    }
  }
  </code></pre>
  
  <p>Now, this works for the first message I send. But then it is not able to make another connection (I get the error message "Bad file descriptor" when trying to connect in the Client program.) Can anyone see what I have misunderstood? Thank you :)</p>