web-dev-qa-db-ja.com

Socket.ioを使用してすべてのクライアントを更新しますか?

Socket.ioを使用してすべてのクライアントを強制的に更新することは可能ですか?私は次のことを試しましたが、新しいクライアントが接続したときに他のクライアントを更新しないようです:

サーバーサイドJavaScript:

現在の接続ユーザー数を含むすべてのクライアントにメッセージを送信しようとしていますが、それはユーザー数を正しく送信します。しかし、クライアント自体はページが更新されるまで更新されないようです。私はこれがリアルタイムで起こることを望んでいます。

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

クライアントサイドJavaScript:

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

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

実際には他のクライアントに更新を送信するのではなく、接続したばかりのクライアントに送信するだけです(最初にロードしたときに更新が表示される理由です)

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

代わりに、allソケットに送信したい

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

または、ブロードキャスト機能を使用して、メッセージを開始するソケットを除く全員にメッセージを送信できます。

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

socket.broadcast.emit()を使用すると、現在の「接続」にのみブロードキャストされることがわかりましたが、io.sockets.emitは、すべてのクライアントにブロードキャストします。ここでは、サーバーは「2つの接続」をリッスンしています。これは、正確に2ソケットですnamespaces

io.of('/namespace').on('connection', function(){
    socket.broadcast.emit("hello");
});
io.of('/other namespace').on('connection',function(){/*...*/});

私はio.sockets.emit()を使用しようとしましたが、他のクライアントで受信されました名前空間。ただし、socket.broadcast.emit()は、現在のソケット名前空間のみをブロードキャストします。

13
houkanshan

Socket.ioバージョン0.9以降、「emit」は機能しなくなり、「send」を使用しています

ここに私がやっていることがあります:

サーバー側

var num_of_clients = io.sockets.clients().length;
io.sockets.send(num_of_clients);

クライアント側:

ws = io.connect...
ws.on('message', function(data)
{
var sampleAttributes = fullData.split(',');
if (sampleAttributes[0]=="NumberOfClients")
        {
            console.log("number of connected clients = "+sampleAttributes[1]);
        }
});
3
Katie
You can follow this example for implementing your scenario.

You can let all of clients to join a common room for sending some updates.
Every socket can join room like this: 

currentSocket.join("client-presence") //can be any name for room

Then you can have clients key in you sockets which contains multiple client's data(id and status) and if one client's status changes you can receive change event on socket like this:

socket.on('STATUS_CHANGE',emitClientsPresence(io,namespace,currentSocket); //event name should be same on client & server side for catching and emiting

and now you want all other clients to get updated, so you can do something like this:

emitClientsPresence => (io,namespace,currentSocket) {
  io.of(namespace)
        .to(client-presence)
        .emit('STATUS_CHANGE', { id: "client 1", status: "changed status" });
}

This will emit STATUS_CHANGE event to all sockets that have joined "client-presence" room and then you can catch same event on client side and update other client's status.
0
Rdavial