Socket.io Connected User Count

后端 未结 12 979
有刺的猬
有刺的猬 2021-01-30 20:24

I finally got socket.io to work properly, but I have encountered a strange problem.

I am not sure if this is the best way, but I am using:

io.sockets.cli         


        
12条回答
  •  没有蜡笔的小新
    2021-01-30 20:57

    I don't see any mention of multi core apps so I'm just gonna add that since I am using multiple cores ( clusters ) I wasn't able to get the right number of sockets consistently on the client side, so I ended up saving them to my mongo instance and it is quite consistent and accurate. With this approach I can view my socket connections in style via the browser :).

    Mongoose schema :

    var socketSchema = mongoose.Schema({
            socket : Number
    });
    

    Usage:

    //reset to 0 when the app starts ( just in case )
    SocketModel.find({ "socket" : 1 } , function(err, deadSockets ) {
        if (err){
            console.log( err );
        }
        else{
            for( var i = 0 ; i < deadSockets.length ; i++ ){
                deadSockets[i].remove();                
            }
        }
    });
    
    io.on('connection', function( socket ) {
        //I found I needed to make sure I had a socket object to get proper counts consistantly
        if( socket ){
            var socketEntry = new SocketModel({ "socket" : 1 });
            socketEntry.save( function(err ){
                if (err){
                    console.log( err );
                }
                else{
            
                }
            });
        }
        //On Disconnect
        socket.on('disconnect', function() {
            SocketModel.findOne({ "socket" : 1} , function(err, deadSocket ) {
                if (err){
                    console.log( err );
                }
                else{
                    deadSocket.remove();
                }
            }); 
        });
    });
    

    How many do I have ?

    SocketModel.count({ "socket" : 1 } , function(err, count ) {
        if (err){
            console.log(err);
        }
        else{
            var term = "sockets";
            if( count == 1 ) term = "socket";
            console.log("Current Load: " , count , term );
        }
    }); 
    

    NOTE I don't like using empty query objects ( {} ) so I just used { "socket" : 1 } as a dummy instead

提交回复
热议问题