Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using node.js to display number of current users

Tags:

node.js

I've somehow managed to scrape together a local node server. All I'm trying to do is when a user connects to the server, to update an integer. I just can't find what keeps track of current users within the node.js code.

if(newUserConnects){
    currentUsers += 1;
}
else if(userDisconnects){
    currentUsers -= 1;
}

I'm very very new to server side programming (I've done a little php, but nothing that interacts directly with sever requests).

like image 663
RustyEight Avatar asked Dec 09 '11 17:12

RustyEight


2 Answers

You probably want to look at using socket.io. It provides hooks into things that can easily count and update the code.

I built an app that does this: http://xjamundx.no.de

The source code is here: https://github.com/xjamundx/CollabPaintJS/blob/master/server.js

See what I do with the count variable.

var count = 0
socket.on('connection', function(client) {
    count++;
    client.broadcast({count:count})
    client.on('disconnect', function(){
        count--;
    })
})

Hope that helps!

The client side code is here: https://github.com/xjamundx/CollabPaintJS/blob/master/public/collabpaint.js

FYI, my app was built with an earlier version of socket.io so the syntax has changed slightly!

like image 169
Jamund Ferguson Avatar answered Sep 25 '22 00:09

Jamund Ferguson


Thank you Jamund, really simple and effective solution. Here is my code:

server.js (Node-0.6.6)

var io = require('socket.io').listen(7777);
var count = 0

io.sockets.on('connection', function(socket) {
    count++;
    io.sockets.emit('message', { count: count });

    io.sockets.on('disconnect', function(){
        count--;
        io.sockets.emit('message', { count: count });
    })
});

client.js (jQuery 1.6.4)

var socket = io.connect('http://domain.com:7777');
socket.on('message', function (data) {
    console.log(data.count);
});
like image 30
3 revs, 2 users 98% Avatar answered Sep 24 '22 00:09

3 revs, 2 users 98%