Home > Software engineering >  How to make a client wait for another client in C
How to make a client wait for another client in C

Time:08-31

I'm developing a simple server/client program.

The server creates a thread for every client who connects. I need to make a client wait for another client to connect to the server, so they can communicate.

Thing is, since every client has a different thread, i can't use join or wait.

What i want is something like:

CLIENT A

Client 1 joins the server

... waiting for another client...

Then, when client 2 connects:

CLIENT B

Client 2 joins the server

Found client 1!

CLIENT A

Found client 2!

I have troubles doing this. I'm using a global list where every client is added when connected. So, my idea was to make every client do something like:

while(1){ 
 // searching the list to find some other clients
}

But doesn't work. Any ideas?

CodePudding user response:

I need to make a client wait for another client to connect to the server, so they can communicate.

It's unnecessary to search for other clients on the client side if you just want to send a message to all clients or just one. Try to add them to a queue on your server and store their connection file descriptor in the client structure. Also, you can use an id for clients if you don't want to just broadcast the message to all clients.

struct Client {
    struct sockaddr_in addr;
    int connfd;   // Connection file descriptor
    int id;
};

struct Client *clients[MAX_CLIENTS];

After establishing the connection and all of this, they can be added to the queue quite easily:

pthread_mutex_t clients_mutex = PTHREAD_MUTEX_INITIALIZER;

void add_to_queue(struct Client *client)
{
    pthread_mutex_lock(&clients_mutex);
    for (int i = 0; i < MAX_CLIENTS;   i) {
        if (!clients[i]) {
            clients[i] = client;
            break;
        }
    }
    pthread_mutex_unlock(&clients_mutex);
}

Whenever a client tries to send a message to other clients, you can just store that message on the server side and forward it to others by their id and just write the message over their connection file descriptor.

void send_msg(char *str, int id)
{
    pthread_mutex_lock(&clients_mutex);
    for (int i = 0; i < MAX_CLIENTS;   i) {
        if (clients[i]) {
            if (clients[i]->id != id) {
                if (write(clients[i]->connfd, str, strlen(str)) < 0) {
                    perror("Write to descriptor failed");
                    break;
                }
            }
        }
    }
    pthread_mutex_unlock(&clients_mutex);
}
  • Related