I want to make a notifications system based on events triggered by a user and gets delivered to another user ('X wrote on your wall). I understand the logic of broadcasting event, but if I broadcast, the message will be sent to everyone on the channel.
I am using Laravel 5 and I used Jeffrey Way's Nodejs, Redis, Socket.io tutorial. Very helpful.
For broadcasting and catching the messages,
Server.js
var server = require('http').Server(); var io = require('socket.io')(server); var Redis = require('ioredis'); var redis = new Redis(); redis.subscribe('globalNotificationChannel'); redis.on('message', function(channel, message) { message = JSON.parse(message); io.emit(channel + ':' + message.event, message.data); }); server.listen(3000);
Client
<script> var socket = io('http://localhost:3000'); socket.on('globalNotificationChannel:WroteOnWall', function(data) { // (Notification Received) // console.log(data.message) }.bind(this)); } <script>
Triggering Action
$data = [ 'event' => 'WroteOnWall', 'data' => [ 'message' => $username + ' wrote on your wall.' ] ]; Redis::publish('globalNotificationChannel', json_encode($data));
Until here everything is clear however at this point I got lost. I have couple of questions.
First, how do I deliver the triggered event to a specific user's channel if everyone gets subscribed on the same channel.
Or is there a way of making unique channels? If so, how can I store the unique_channel_ids to prevent any bug?
And secondly, I have seen people are using cluster. Is it a good use for my case? Will it give me any benefits to me?
Note that on the Client side, I inserted it in master page as I need to run in every page, but now, I need to call 'connection' and 'listening' in every page. When re-run the connection scripts won't I end up with differing socketids?
Edit: I found this SO answer, and I believe it solves my problem, but I couldn't adapt it on redis instance.