当前位置: 动力学知识库 > 问答 > 编程问答 >

Using node.js to display number of current users

问题描述:

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);
});
网友答案:

Tested and works with:

  • Node v0.12.2 (server)
  • Socket.io v0.9.17 (server)
  • jQuery v1.11.3 (client)

server.js

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

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

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

client.js

var socket = io.connect('http://localhost:8080');
socket.on('message', function (data) {
    console.log(data.count);
});
分享给朋友:
您可能感兴趣的文章:
随机阅读: