首页 > 解决方案 > Node js socket.io 仅针对特定事件订阅广播

问题描述

现在我在 Laravel 中有一个小程序,通过事件服务于股市价格。当费率得到更新时,它会将费率更新到 redis 并从节点 js 应用程序广播到客户端。

在这里,我创建了 3 个事件,如盎司汇率、MCX 汇率和 Comex 汇率。我的 socket.io 程序就像这样,

redis.subscribe('mcxratesupdate', function(err, count) {
    
});

redis.subscribe('ounceratesupdate', function(err, count) {
    
});

redis.subscribe('comexratesupdate', function(err, count) {
    
});

redis.on('message', function(channel, message) {
    message = JSON.parse(message);
    io.emit(channel + ':' + message.event, message.data);
});

server.listen(3002, function(){
    console.log('Listening on Port 3002');
});

在我的客户有这样的代码,

$(function () {
    var socket = io.connect('http://myhost:3002/', { secure: true, transports: ['websocket'], rejectUnauthorized: false, reconnect: true });
    socket.on("mcxratesupdate:App\\Events\\MCXRateUpdates", function(data){
        console.log(data);
    });
});

这工作正常,但如果事件 ounceratesupdate get 触发该响应也会广播到该客户端。所以这个单一服务器数据中的所有事件都被广播到客户端。如何避免所有事件数据共享,只共享特定事件数据。

标签: phpnode.jslaravel-5socket.ioevent-handling

解决方案


推荐阅读