dimanche 22 novembre 2015

How do chat servers distribute messages to multiple clients?

This is really a programming design question more than a specific language or library question. I'm tinkering with the idea of a standalone chat server for websockets that will accept several remote browser-based javascript clients. I'm going for something super simple at first, then might build it up. The server just keeps accepting client connections and listens for messages. When a message is received, it will be sent back to all the clients.

What I need to better understand is which approach is best for sending the messages out to all clients, specifically, sending immediately to all clients, or queuing the messages to each client's queue to be sent when a client connection handler's turn comes up. Below are the two examples in a python-like pseudo-code:

Broadcast Method

def client_handler(client):
    while true:
        if(client.pending_msg):
            rmsg = client.recv()
            for c in clients:
                c.send(rmsg)
        client.sleep(1)

Queue Method

def client_handler(client):
    while true:
        if client.pending_msg:
            rmsg = client.recv()
            for c in clients:
                c.queue_msg(rmsg)
        if client.has_queued:
            client.send_queue
        client.sleep(1)

What is the best approach? Or, perhaps they are good for different use-cases, in which case, what are the pros, cons and circumstances for which they should be used. Thanks!

Aucun commentaire:

Enregistrer un commentaire