jeudi 29 avril 2021

Node js socket.io broadcast only for particular events subscription

Now I have a small program in Laravel to serve the stock market rates via events. When ever the rates gets update it will update the rates to redis and broadcast from node js application to clients.

Here I have created 3 events like ounce rate, MCX rates and comex rates. My socket.io program as like,

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

In my client having the code like,

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

This is working fine, But if the event ounceratesupdate get fires that response also broadcast to this client. So all the events in this single server data getting broadcast to client. How to avoid all the events data sharing and only share particular event data.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire