Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Using node.js to display number of current users

Using node.js to display number of current users

Problem

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).

Problem courtesy of: RustyEight

Solution

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!

Solution courtesy of: Jamund Ferguson

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Using node.js to display number of current users

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×