V
V
Vmedmen2018-03-31 00:33:00
Yii
Vmedmen, 2018-03-31 00:33:00

What is the correct way to send notifications to multiple tabs using socket.io?

Friends, good afternoon.
Faced a very interesting task (perhaps only for me). I implement notifications using socket.io, redis. All this is spinning on yii2.
Essence of the question. When sending a notification to a user, notifications are duplicated. The number of duplicate notifications depends on the number of open tabs.
Client part. Here we create a room for the user and subscribe to notifications.

var socket = io();
socket.emit("join", {"room": userRoom});
socket.on("notify", function (data) {
     $( "#notifications" ).prepend(data.message);
});

Server part.
io.on('connection', function (socket) {
        var redisClient = redis.createClient(6379, 'redis');
        redisClient.subscribe('notify');
        redisClient.on("message", function(channel, message) {
            var res = JSON.parse(message);
            io.sockets.in(res.room).emit(channel, {msg: res.message});
        });
        socket.on('disconnect', function() {
            redisClient.quit();
        });
    });

How the notification is sent.
Yii::$app->redis->executeCommand('PUBLISH', [
    'channel' => 'notify',
    'message' => \yii\helpers\Json::encode(['room' => 'room', 'message' => 'hello'])
]);

Actually works well. But the more I open browser tabs, the more I get duplicate messages in one tab. For example, I have 5 tabs open. I initiate executeCommand once and pass hello message. Thus, in each of the 5 tabs, 5 words "Hello" appear. At the same time, I look through the redis-cli monitor and see that only one notification is being created.
Thanks in advance for the hint.
Thanks

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question