Reputation: 323
I'm quite new to Redis Pub/sub so please bear with me. I'm trying to create an IRC where users can create their own chat rooms, kinda like Gitter. Below is what I've done so far.. I'm subscribing the users to different channels by their username only just for testing.. Thing is that when I publish to channel x, a client who's subbed to channel y still gets the same message.. I'm publishing using redis-cli and PUBLISH command.
function handleIO(socket){
function disconnect(){
console.log("Client disconnected");
socket.broadcast.emit("user d/c", socket.username+" has left!");
}
socket.on("new user", function(username){
socket.username = username;
if(socket.username == "chat"){
redisClient.subscribe("chat");
}else{
redisClient.subscribe("other");
}
socket.userColor = '#'+(Math.random()*0xFFFFFF<<0).toString(16);
socket.emit("new_user", username);
emitter.lrange("messages", 0, -1, function(err, messages){
//reversing to be in correct order
messages = messages.reverse();
messages.forEach(function(message){
message = JSON.parse(message);
socket.emit("messages", message);
});
});
socket.broadcast.emit("user connection", username+" has connected to the Haven!");
});
socket.on("disconnect", disconnect);
socket.on("send", function(msg){
var msg = JSON.stringify( { name: socket.username, messageText: msg, color: socket.userColor } );
emitter.lpush("messages", msg, function(err, response){
//keep newest 10 items
emitter.ltrim("messages", 0, 9);
});
io.sockets.emit("receive", msg, socket.userColor);
});
redisClient.on("message", function (channel, message) {
console.log(channel+":"+message);
socket.emit("message", channel, message);
});
}
Upvotes: 0
Views: 1083
Reputation: 323
For the lost wanderer out there... What I did is implement another event on the client to basically check whether that client is 'entitled' to the message (i.e. whether the message's channel belongs in the client's list of subbed channels if that makes sense).
Client-side
socket.on("message", function(channel, message){
socket.emit("entitled", channel, message);
});
socket.on("entitled", function(reply, channel, message){
if(reply == 1){
$("#msgArea").append(message+"<br/>");
$("#msgArea").prop({ scrollTop: $("#msgArea").prop("scrollHeight") });
}
});
Server-side
socket.on("entitled", function(channel, message){
//check that user is subbed
emitter.sismember('channels:'+socket.username, channel, function(err, reply){
if(err) throw err;
socket.emit("entitled", reply, channel, message);
});
});
What I purposely left out is that I didn't keep using socket.username but started using sessions for persistence.. My word of advice would be to stick with redis store since it's one of the most popular on github.
Upvotes: 1