Node.js   发布时间:2022-04-24  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了node-websocket-server:可能有单个node.js进程的多个,单独的“广播”?大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我想知道是否可以广播在不同的websocket“连接”运行从同一个 node-websocket-server应用程序实例。想象一下,具有多个房间的聊天室服务器,仅在单个node.js服务器进程上向特定于每个房间的参与者广播消息。我已经成功地实现了一个单聊天室的进程解决方案,但我想把它提高到一个新的水平。

解决方法

你可能想尝试Push-it: http://github.com/aaronblohowiak/Push-It它建立在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({@R_489_8798@ge: 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({@R_489_8798@ge: msg});
         }
      }
}

为了使它更容易使用EventEmitters。因此,在Node-websocket-server / Socket.IO中,查看消息被接收到的地方,并解析消息以检查类型(subscribe / unsubscribe / publish),并根据类型发出带有消息的事件。例:

Client.prototype._on@R_489_8798@ge = function(@R_489_8798@gE) {
       switch(@R_489_8798@ge.typE) {
         case 'subscribe':
             this.emit('subscribe',@R_489_8798@ge.chAnnel);
         case 'unsubscribe':
             this.emit('unsubscribe',@R_489_8798@ge.chAnnel);
         case 'publish':
             this.emit('publish',@R_489_8798@ge.chAnnel,@R_489_8798@ge.data);
         default:

       }
}

聆听您应用程式中所发出的活动(「连线」):

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,@R_489_8798@gE) {
     client.publish(chAnnel,@R_489_8798@gE);
});

希望这可以帮助。

大佬总结

以上是大佬教程为你收集整理的node-websocket-server:可能有单个node.js进程的多个,单独的“广播”?全部内容,希望文章能够帮你解决node-websocket-server:可能有单个node.js进程的多个,单独的“广播”?所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。