使用Socket.io更新所有客户端? [英] Update all clients using Socket.io?

查看:152
本文介绍了使用Socket.io更新所有客户端?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用socket.io强制所有客户端更新?我尝试了以下方法,但是当新客户端连接时似乎没有更新其他客户端:

Is it possible to force all clients to update using socket.io? I've tried the following, but it doesn't seem to update other clients when a new client connects:

我正在尝试向所有客户端发送一条消息,其中包含当前已连接用户的数量,它正确地发送了一定数量的用户....但是客户端本身似乎没有更新,直到页面已刷新。我希望这是实时的。

I'm attempting to send a message to all clients, which contains the current number of connected users, it correctly sends the amount of users.... however the client itself doesn't seem to update until the page has been refreshed. I want this to happen is realtime.

var clients = 0;
io.sockets.on('connection', function (socket) {
  ++clients;
  socket.emit('users_count', clients);    
  socket.on('disconnect', function () {
    --clients;
  });
});



Clientside JavaScript:



Clientside JavaScript:

var socket = io.connect('http://localhost');

socket.on('connect', function(){
  socket.on('users_count', function(data){
    $('#client_count').text(data);
    console.log("Connection");
  });
});


推荐答案

它实际上并没有向其他客户发送更新所有,相反它只是向刚刚连接的客户端发出(这就是你第一次加载时看到更新的原因)

It's not actually sending an update to the other clients at all, instead it's just emitting to the client that just connected (which is why you see the update when you first load)

// socket is the *current* socket of the client that just connected
socket.emit('users_count', clients); 

相反,您要发送到所有套接字

Instead, you want to emit to all sockets

io.sockets.emit('users_count', clients);

或者,你可以使用广播功能,它向除了启动它的套接字以外的所有人发送消息:

Alternatively, you can use the broadcast function, which sends a message to everyone except the socket that starts it:

socket.broadcast.emit('users_count', clients);

这篇关于使用Socket.io更新所有客户端?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆