栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

希望这可以帮助。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/484636.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号