Search code examples
cserverclientposix-select

Block a client without blocking others in Select


I have to create a program with two parts: Client / Server.

I receive commands from different clients and I want to put the client waiting during the command is executed, but, the other clients must be able to send command to the server

e.g : C1 (for client 1) and C2 (for client 2)

C1 send command -> server receive it and execute it and he can't accept command from C1 for x seconds but he can accept command from the C2.

How can I do it with select function without threads?

This is my current code from the server :

void            client_ask(t_listplayer *list, t_network *net) {
  char          *buffer = xmalloc(sizeof(char) * 200);
  int           rd = 0;

  memset(buffer, 0, 200);
  while (list != NULL) {
      if (FD_ISSET(list->player->fd, &net->readfds)) {
          if ((rd = xread(list->player->fd, buffer, 200)) > 0) {
              buffer[rd - 1] = '\0';
              printf("Client n°: %d asking : [%s]\n", list->player->fd, buffer);
              sleep(3); // This one put all the server in waiting
              memset(buffer, 0, 200);
            } else {
              close(list->player->fd);
              printf("Client n°: %d has just disconnected", list->player->fd);
            }
        }
      list = list->next;
    }
}

So, I've made many researches .. I've heard things about timeout but I don't know how to do this.


Solution

  • You could manage client-states in your list of clients. If the client state is 'wait', do not answer it (or better : answer "you must wait for x" or some useful feedback). All the clients will be able to send requests and only the one in the correct states will be processed.

    Do not forget to reset the client's state when your work is done on its request.