Answer the question
In order to leave comments, you need to log in
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);
});
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();
});
});
Yii::$app->redis->executeCommand('PUBLISH', [
'channel' => 'notify',
'message' => \yii\helpers\Json::encode(['room' => 'room', 'message' => 'hello'])
]);
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question