无法更新已连接的用户数(Node.js& Socket.io)

时间:2016-04-03 20:36:58

标签: node.js socket.io ecmascript-6

使用vanilla node.js测试socket.io,我正在创建一个简单的应用程序来显示在线用户数,使用窗口标题来简化。它在服务器的控制台端工作正常,但是当我打开一个新选项卡时,它不会在客户端的浏览器上更新。这有什么问题?这是代码:

var html = `
    <script src="/socket.io/socket.io.js"></script>
    <script>
        var socket = io();
        socket.on('count updated', (data) => {
            //Worked on the current tab, didn't updating on the other tabs
            document.title = data + ' User(s) Online';
        });
    </script>
`;

var count = 0;    

var server = require('http').createServer((req, res) => {
    res.end(html);
});

var io = require('socket.io')(server).on('connection', (socket) => {

    console.log(`${++count} User(s) Online`); //worked fine
    socket.emit('count updated', count); //worked once

    socket.on('disconnect', () => {
        console.log(`${--count} User(s) Online`); //worked fine
        socket.emit('count updated', count); //didn't worked
    });
});

server.listen(80);

2 个答案:

答案 0 :(得分:2)

你不能像那样发射到刚断开的插座。您可以然后将计数广播给所有连接的用户。为此,请将socket.emit('count updated', ..)的实例替换为:

io.sockets.emit('count updated', count);

甚至更简单:

io.emit('count updated', count);

答案 1 :(得分:0)

基于socket.io的示例: https://github.com/socketio/socket.io/blob/master/examples/chat/index.js

您可以使用socket.broadcast.emit('count updated', count)