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).
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!
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);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With