Search code examples
node.jspipeserversocket

NodeJS Chat Server Broadcast : Pipe vs Write


I'm trying to make a simple chat server for friends/office which will at anytime have a maximum of 50 people connected.

  • A user's message is broadcast to all connected users
  • Server is based on 'net' (TCP/IP) (Will move into 'http' server later on)
  • Users connect to server via Telnet

Which of the below methods is good practice to broadcast messages in terms of efficiency and/or reliability?

  • Pipe all users to one another (or)
  • Upon receiving data, write to all users other than itself?

Example Pipe Server:

    var server = net.createServer(function(socket) {
        for(var i=0; i<sockets_list.length; i++){
            socket.pipe(sockets_list[i]);
            sockets_list.pipe(socket);
        }
        sockets_list.push(socket);
    });

Example Write Server:

    var server = net.createServer(function(socket) {
        sockets_list.push(socket);

        socket.on('data', function(data){
            for(var i=0; i<sockets_list.length; i++){
                if(socket != sockets_list[i]){
                    sockets_list[i].write(data);
                }
            }
        });            
    });

Solution

  • This pipe solution seems to be very wrong for at least three reasons:

    1. You have no control over data (security, validation, authentication, parsing, etc.). That's the most important reason for not going that way. You may not need it now but you will need it in future. Otherwise I'll just connect to your server and kill it simply by spamming. ;)
    2. Newly added socket will send data to existing sockets but how will existing sockets send data to the newly added one? The logic gets complicated at that point (you have to store destinations for each socket and update all of them whenever new connection happens). Not to mention that with that solution you won't be able to send data to only one socket. It's a restriction you don't want.
    3. You have no control over reading/writing frequency (yes, I know that .pipe handles it somehow but I don't how and how reliable it is). You don't have to read/write every time data is available. In fact you should not. You should always consider a minimal time between consecutive reads/writes. It will be more efficient and secure (and having a lag for say half a second is not a big deal for a user, he won't even notice it).