gpt4 book ai didi

node.js - node-websocket-server : possible to have multiple, 单独的 "broadcasts"用于单个 node.js 进程?

转载 作者:IT老高 更新时间:2023-10-28 21:51:36 25 4
gpt4 key购买 nike

我想知道是否可以在从同一个 node-websocket-server 运行的不同 websocket“连接”上进行广播应用实例。想象一个有多个房间的聊天室服务器,仅在单个 node.js 服务器进程上向特定于每个房间的参与者广播消息。我已经成功实现了一个每个进程一个聊天室的解决方案,但我想将它提升到一个新的水平。

最佳答案

您可能想试试 Push-it:http://github.com/aaronblohowiak/Push-It它建立在 Socket.IO 之上。设计遵循巴约协议(protocol)。

但是,如果您需要使用 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});
}
}
}

因此,如果您只想将消息中继到特定 channel ,只需维护客户端订阅的所有 channel 的列表即可。这是一个简单的例子(让你开始):

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

希望这会有所帮助。

关于node.js - node-websocket-server : possible to have multiple, 单独的 "broadcasts"用于单个 node.js 进程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4445883/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com