[Node.js] How to keep all connections connected with this server app

Discussion in 'JavaScript' started by ketting00, Apr 20, 2015.

  1. #1
    Hi guys,

    I'm not sure if this the right place to ask. Since I cannot post it on Google Group I would post it here in hope someone can help me out.

    Below is my simple node.js server app. It broadcasts message from a sending user to all connected users. However, all connections have been lost if somebody refresh a page. I hope somebody can point out what wrong with my code. How do I keep connections connected.
    
    var WebSocketServer = require('ws').Server;
    
    var wsServer = new WebSocketServer({ port : 8080 }),
        clients = [];
    
    wsServer.on('connection', function(ws) {
        clients.push(ws);
    
        ws.on('message', function(message, flags) {
            for(var i = 0, j = clients.length; i < j; i += 1) {
                var xx = clients[i];
            }
            if (typeof message === 'string') {
                var json = JSON.parse(message);
                switch(json.type) {
                    case "msg":
                        broadcast.data(xx, message);
                        break;
                    case "data":
                    case "demo":
                        // return;
                        break;
                }
            }
        });
    
        ws.on('close', function(message) {
            var index = clients.indexOf(ws);
            if (index !== -1) {
                clients.splice(index, 1);
            }
        });
    });
    
    // Broadcast messages to all connected clients
    var broadcast = {
        data: function(xi, message) {
            var that = this;
            this.xi = xi;
            this.message = message;
            this.data.prototype = function() { that.send(this.xi, this.message); }
            this.data.prototype(this.xi, this.message);
        },
        send: function(){
            this.xi.send(this.message, {
                mask: false
            });
        }
    };
    
    Code (markup):
    Thanks,
     
    ketting00, Apr 20, 2015 IP
  2. ketting00

    ketting00 Well-Known Member

    Messages:
    782
    Likes Received:
    28
    Best Answers:
    3
    Trophy Points:
    128
    #2
    Ha ha,
    I was able to solve this eventually. What's a challenge :) Exciting!
     
    ketting00, May 3, 2015 IP
  3. PoPSiCLe

    PoPSiCLe Illustrious Member

    Messages:
    4,623
    Likes Received:
    725
    Best Answers:
    152
    Trophy Points:
    470
    #3
    I would recommend you show us what you did to solve it - it might help other people struggling with the same problem, finding your post on a search. It's customary to include solutions you come up with yourself (with a source if it's pulled from somewhere).
     
    PoPSiCLe, May 3, 2015 IP
  4. ketting00

    ketting00 Well-Known Member

    Messages:
    782
    Likes Received:
    28
    Best Answers:
    3
    Trophy Points:
    128
    #4
    OK, this is how I do with my (actually) single page application (not that mile long one). It read file on a server and sent data from there with a lightning speed (believe me, there's a guy trying to send data at a light speed). It helps eliminated the need of page refresh and HTTP request overhead.

    The problems were that it has to wait for a handshake and websocket connection to establish and it comes at a cost of server memory. There's problem with SEO though, Uncle Google may not index those information and you lose ranking. I don't care since my files are mostly media.

    Aside form that, everything is fine and I'm very happy with it.

    If you look at the code below and spot anything I can improve my code it's greatly appreciated. I'm always looking for best practice:
    Here it is (security included for a noob interesting in Node.js):
    
    var wsServer = new WebSocketServer({ port : 8080 }),
        clients = [];
    
        wsServer.on('connection', function(ws) {
            clients.push(ws);
    
            var domain = ws.upgradeReq.headers.origin;
            if (domain !== 'http://mywebsite.com') {
                return;
            }
    
            ws.on('message', function(message, flags) {     
                if (typeof message === 'string') {
                    var json = JSON.parse(message);
                    switch(json.type) {
                        case "msg":
                            var req = json.data.request,
                            user = json.data.user;
                            fs.readFile(__dirname + '/files/' + req, 'utf-8', function(err,data){
                                if (err) { return console.log(err); }
                                var cont = { user: user, data: data },
                                    object = JSON.stringify({ type:'script', data: cont });
    
                                for (var i = 0, j = clients.length; i < j; i += 1) {
                                    var z = clients[i],
                                    sendIt= new sendData(z);
                                }
                                function sendData(z) {
                                    broadcast.data(z, object);
                                }
                            });
                            break;
                        case "data":
                        case "demo":
                            // do something else
                            break;
                    }
                }
            });
        });
    
    Code (markup):
     
    ketting00, May 3, 2015 IP
    ThePHPMaster likes this.