node-websocket-server:单个node.js进程可能有多个单独的“广播”吗?

node-websocket-server:单个node.js进程可能有多个单独的“广播”吗?,第1张

node-websocket-server:单个node.js进程可能有多个单独的“广播”吗?

您可能想尝试Push-it:http :
//github.com/aaronblohowiak/Push-It,它建立在Socket.IO之上。设计遵循贝叶协议。

但是,如果您需要使用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 clientClient.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中,查看在何处接收消息并解析消息以检查类型(订阅/取消订阅/发布),并根据类型发出带有消息的事件。例:

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);});

希望这可以帮助。



欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5476776.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-12
下一篇 2022-12-12

发表评论

登录后才能评论

评论列表(0条)

保存