title: C Sockets Client/Server pthreads server broadcast
body: <p>We were given this code, and was supposed to modify it so that whenever a client connects to a server and sends a message the server should reply I hear you dude. That is working for one and multiple clients but next task was to when ever a new client connects the server should tell that to all the other clients that are connected.</p>
  
  <p>I assumed this would be fairly easy but its not working out like I thought it would. Since the server always get sock 3 and first client gets 4 and second client gets 5 etc, I tried to make a for loop that messaged whenever a new client connects the loop will send message to 4,5 which just made the server close itself directly. I then tried to just make when ever a new client connects that the server should message the first client(4) which it actually does but only if client(4) writes a message to the server he recieves that broadcast that the server sent.</p>
  
  <p>So it seems like the client wants to write but needs to write something before he recieves the broadcast from the server, any help would appreciated since we're kinda beginners with all this.</p>
  
  <p>This is how the code looks like at the moment.</p>
  
  <p>server.c</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;errno.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;unistd.h&gt;
  #include &lt;sys/types.h&gt;
  #include &lt;sys/socket.h&gt;
  #include &lt;sys/times.h&gt;
  #include &lt;arpa/inet.h&gt;
  #include &lt;netinet/in.h&gt;
  #include &lt;netdb.h&gt;
  #include &lt;string.h&gt;
  #include &lt;pthread.h&gt;
  
  #define PORT 5555
  #define MAXMSG 512
  
  
  void *connection_handler(void *socket_desc)
  {
      int sock = *(int*)socket_desc;
      int read_size;
      char *message, client_message[2000], *message_to_client;
      message = "Greetings! I am your connection handler\n";
      write(sock, message, strlen(message));
      while( (read_size = recv(sock, client_message, 2000, 0)) &gt; 0)
      {
         client_message[read_size] = '\0';
         printf("Client[%d]: %s", sock, client_message);
         message_to_client = "I hear you dude...";
         write(sock, message_to_client, 19);
         memset(client_message, 0, 2000);
      }
  
      if(read_size == 0)
      {
         printf("Client[%d] disconnected", sock);
         fflush(stdout);
      }
      else if(read_size == -1)
      {
         perror("recv failed");
  
      }
      free(socket_desc);
      return 0;
  }
  
  int makeSocket(unsigned short int port) {
      int sock;
      struct sockaddr_in name;
      /* Create a socket. */
      sock = socket(PF_INET, SOCK_STREAM, 0);
      if(sock &lt; 0) {
          perror("Could not create a socket\n");
          exit(EXIT_FAILURE);
      }
      name.sin_family = AF_INET;
      name.sin_port = htons(port);
      name.sin_addr.s_addr = htonl(INADDR_ANY);
      if(bind(sock, (struct sockaddr *)&amp;name, sizeof(name)) &lt; 0) {
          perror("Could not bind a name to the socket\n");
          exit(EXIT_FAILURE);
      }
      return(sock);
  }
  
  int main(int argc, char *argv[])
  {
      int sock;
      int clientSocket;
      int i;
      int *new_sock;
      char *broadcast;
      fd_set activeFdSet, readFdSet;
      struct sockaddr_in clientName;
      socklen_t size;
      sock = makeSocket(PORT);
      if(listen(sock,1) &lt; 0) 
      {
          perror("Could not listen for connections\n");
          exit(EXIT_FAILURE);
      }
      FD_ZERO(&amp;activeFdSet);
      FD_SET(sock, &amp;activeFdSet);
      while(1) 
      {
          printf("Waiting for connections\n");
          readFdSet = activeFdSet;
          if(select(FD_SETSIZE, &amp;readFdSet, NULL, NULL, NULL) &lt; 0)
          {
              perror("Select failed\n");
              exit(EXIT_FAILURE);
          }
          for(i = 0; i &lt; FD_SETSIZE; ++i)
          {
              if(FD_ISSET(i, &amp;readFdSet)) 
              {
                  if(i == sock) 
                  {
                      size = sizeof(struct sockaddr_in);
                      pthread_t sniffer_thread;
                      while(( clientSocket = accept(sock, (struct sockaddr *)&amp;clientName, (socklen_t *)&amp;size))) 
                      {
                          puts("Connection accepted");
                          new_sock = malloc(1);
                          *new_sock = clientSocket;
                          if( pthread_create( &amp;sniffer_thread, NULL, connection_handler, (void*) new_sock) &lt; 0)
                          {
                              perror("could not create thread");
                              return 1;
                          }
                          broadcast = "NEW CLIENT CONNECTED";
                          write(4, broadcast, sizeof(broadcast)); //just to see if when ever a new client connects the first client should get all these messages
                          write(4, broadcast, sizeof(broadcast));
                          write(4, broadcast, sizeof(broadcast));
                          pthread_detach(sniffer_thread);
                          puts("Handler assigned");
                          FD_SET(*new_sock, &amp;activeFdSet);
  
                     }
                     if(clientSocket &lt; 0) 
                     {
                         perror("Could not accept connection\n");
                         exit(EXIT_FAILURE);
                     }                
                  }
                  else 
                  {
                      if(readMessageFromClient(i) &lt; 0)
                      {
                      close(i);
                          FD_CLR(i, &amp;activeFdSet);
                      }
                  }
              }
          }      
      }
  } 
  </code></pre>
  
  <p>and for the client the code looks like this</p>
  
  <p>client.c</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;errno.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;string.h&gt;
  #include &lt;unistd.h&gt;
  #include &lt;sys/types.h&gt;
  #include &lt;sys/socket.h&gt;
  #include &lt;netinet/in.h&gt;
  #include &lt;netdb.h&gt;
  
  #define PORT 5555
  #define hostNameLength 50
  #define messageLength  256
  
  void initSocketAddress(struct sockaddr_in *name, char *hostName, unsigned short int port) 
  {
    struct hostent *hostInfo; 
    name-&gt;sin_family = AF_INET;
    name-&gt;sin_port = htons(port);
    hostInfo = gethostbyname(hostName);
    if(hostInfo == NULL)
    {
      fprintf(stderr, "initSocketAddress - Unknown host %s\n",hostName);
      exit(EXIT_FAILURE);
    }
    name-&gt;sin_addr = *(struct in_addr *)hostInfo-&gt;h_addr;
  }
  void writeMessage(int fileDescriptor, char *message) 
  {
    int nOfBytes;
    nOfBytes = write(fileDescriptor, message, strlen(message) + 1);
    if(nOfBytes &lt; 0) 
    {
      perror("writeMessage - Could not write data\n");
      exit(EXIT_FAILURE);
    }
  }
  
  int main(int argc, char *argv[]) 
  {
    int sock;
    struct sockaddr_in serverName;
    char hostName[hostNameLength];
    char messageString[messageLength];
    char buffer[1024];
    if(argv[1] == NULL) 
    {
      perror("Usage: client [host name]\n");
      exit(EXIT_FAILURE);
    }
    else 
    {
      strncpy(hostName, argv[1], hostNameLength);
      hostName[hostNameLength - 1] = '\0';
    }
  
    sock = socket(PF_INET, SOCK_STREAM, 0);
    if(sock &lt; 0) 
    {
      perror("Could not create a socket\n");
      exit(EXIT_FAILURE);
    }
  
    initSocketAddress(&amp;serverName, hostName, PORT);
    if(connect(sock, (struct sockaddr *)&amp;serverName, sizeof(serverName)) &lt; 0) 
    {
      perror("Could not connect to server\n");
      exit(EXIT_FAILURE);
    }
    printf("\nType something and press [RETURN] to send it to the server.\n");
    printf("Type 'quit' to nuke this program.\n");
    fflush(stdin);
    recv(sock, buffer, 1024, 0);
    printf(buffer);
    while(1) 
    {
      printf("\n&gt;");
        fgets(messageString, messageLength, stdin);
        messageString[messageLength - 1] = '\0';
        if(strncmp(messageString, "quit\n",messageLength) != 0)
           writeMessage(sock, messageString);
        if(recv(sock, buffer, 1024, 0) &gt; 0)
                 printf(buffer);
  
  
    }
  }
  </code></pre>