node-websocket-server: 単一の node.js プロセスに対して複数の個別の「ブロードキャスト」を実行することは可能ですか? 質問する

node-websocket-server: 単一の node.js プロセスに対して複数の個別の「ブロードキャスト」を実行することは可能ですか? 質問する

同じWebSocketから異なるWebSocket「接続」でブロードキャストできるかどうか知りたいです。ノードウェブソケットサーバーアプリ インスタンス。複数のルームを持つチャット ルーム サーバーを想像してください。単一の node.js サーバー プロセスで、各ルームに固有の参加者にのみメッセージをブロードキャストします。プロセスごとに 1 つのチャット ルームのソリューションを正常に実装しましたが、これを次のレベルに進めたいと思います。

ベストアンサー1

おそらく、Push-it を試してみたいと思います:http://github.com/aaronblohowiak/プッシュイットSocket.IO 上に構築されています。設計は Bayeux プロトコルに準拠しています。

ただし、Redis PubSubを使用する必要があるときは、http://github.com/shripadk/Socket.IO-PubSub

具体的にあなたの質問にお答えします。Websocket サーバーに接続されているすべてのクライアントの配列を維持できます。そして、おそらくそれらのクライアントのサブセットにブロードキャストするだけでしょうか? ブロードキャスト メソッドは、基本的にそれを裏で行います。node-websocket-server/Socket.IO は、接続されているすべてのクライアントの配列を維持し、それらすべてをループして各クライアントにメッセージを「送信」します。コードの要点:

// considering you storing all your clients in an array, should be doing this on connection:
clients.push(client)

// loop through that array to send to each client
Client.prototype.broadcast = function(msg, except) {
      for(var i in clients) {
          if(clients[i].sessionId !== except) {
             clients[i].send({message: msg});
          }
      }
}

したがって、特定のチャネルにのみメッセージを中継したい場合は、クライアントがサブスクライブしているすべてのチャネルのリストを維持するだけです。以下は簡単な例です (開始するためのものです) :

clients.push(client);


Client.prototype.subscribe = function(channel) {
      this.channel = channel;
}

Client.prototype.unsubscribe = function(channel) {
     this.channel = null;
}

Client.prototype.publish = function(channel, msg) {
      for(var i in clients) {
         if(clients[i].channel === channel) {
            clients[i].send({message: msg});
         }
      }
}

さらに簡単にするには、EventEmitters を使用します。node-websocket-server/Socket.IO で、メッセージが受信されている場所を確認し、メッセージを解析してタイプ (subscribe/unsubscribe/publish) を確認し、タイプに応じてメッセージを含むイベントを発行します。例:

Client.prototype._onMessage = function(message) {
       switch(message.type) {
         case 'subscribe':
             this.emit('subscribe', message.channel);
         case 'unsubscribe':
             this.emit('unsubscribe', message.channel);
         case 'publish':
             this.emit('publish', message.channel, message.data);
         default:

       }
}

アプリの on('connection') で発行されたイベントをリッスンします。

client.on('subscribe', function(channel) {
     // do some checks here if u like
     client.subscribe(channel);
});
client.on('unsubscribe', function(channel) {
     client.unsubscribe(channel);
});
client.on('publish', function(channel, message) {
     client.publish(channel, message);
});

お役に立てれば。

おすすめ記事