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

用vanilla node.jstestingsocket.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); 

你不能像这样发射到刚刚断开的套接字。 但是,您可以将计数广播给所有连接的用户。 为此,将socket.emit('count updated', ..)实例replace为:

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

甚至更简单:

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

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

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