How can I have different web browsers subscribe to separate channels in a Redis/Node.js/Soc…

I’d like different clients (web browsers) to be able to subscribe to separate Redis channels.

I’m able to pass the requested channel from the client page to the node.js
server. But, if I have three browsers subscribe each subscribe three separate channels, all three browsers receive messages published to any of the three channels.

Here is the client HTML code. I have three separate pages with the channel name hardcoded into it. In this example, the channel is “channel1”.

client1.html


var socket = io.connect('http://localhost');
socket.on('giveChannel', function () {
    console.log('sending channel');
    socket.emit('sendChannel', "{"channel":"channel"}");
});

socket.on('message', function (data) {
    console.log(data);
});

Here is the Node.js
file.

app.js

redis = require('redis'),
sys = require('sys');
var http = require('http');
var url = require('url');
var fs = require('fs');

var server = http.createServer(function (req, res) {
    var path = url.parse(req.url).pathname;
    fs.readFile(__dirname + path, function(err, data) {
        if (err) return null;
        res.writeHead(200, {'Content-Type': 'text/html'});
        res.write(data, 'utf8');
        res.end();
    });

});

io = require('socket.io').listen(server);

io.sockets.on('connection', function (socket) {
    var rc = redis.createClient();

    rc.on("connect", function() {
        sys.log('connected to redis');
    });

    rc.on("message", function (channel, message) {
        sys.log("Sending: " + message);
        io.sockets.emit('message', message);
    });

    socket.emit('giveChannel');
    socket.on('sendChannel', function (msg) {
        console.log(msg);
        var data = JSON.parse(msg);
        console.log(data.channel);
        rc.subscribe(data.channel);
    });
});

server.listen(8000, '0.0.0.0');

Problem courtesy of: messick

Solution

As per your example APP will open a new redis connection per every user,that doesn’t make sense.

This use one connection for entire app (you have to make one more connection for publish the data) for sub jobs

Client Side

var socket = io.connect('http://localhost:3000');

socket.emit('channel','US');
socket.on('news',function(news){
    $("body").append('
' + news); }); socket.on('message',function(msg){ $("body").append('
' + msg); });

Server Side

var io      = require('socket.io');
var express = require('express');
var app     = express.createServer();

io = io.listen(app);

app.listen('3000');
var pub = require('node_redis').createClient(); //publish cli
var redis = require('node_redis').createClient(); //sub cli
redis.psubscribe('*');  

redis.on('pmessage',function(pat,ch,msg){
    io.sockets.in(ch).emit('news',msg);
});

io.sockets.on('connection',function(socket){
    console.log('Socket connected: ' + socket.id);

    socket.on('channel',function(ch){
        socket.join(ch)

         //Publishing data on ch
         pub.publish(ch,"Hello " + ch);  
    });


    socket.on('disconnect',function(){
        console.log('Socket dis connected: ' + socket.id);
    });
});


console.log('Server started @ 3000');

Solution courtesy of: Ganesh Kumar

您可能感兴趣的

Linux编程之select select系统调用的的用途是:在一段指定的时间内,监听用户感兴趣的文件描述符上可读、可写和异常等事件。 select 机制的优势 为什么会出现select模型? 先看一下下面的这句代码: int iResult = recv(s, buffer,1024); 这是用来接收...
伯克利推出世界最快的KVS数据库Anna:秒杀Redis和Cassandra... 天下武功,唯快不破。 伯克利 RISE 实验室推出了最新的键值存储数据库 Anna,提供了惊人的存取速度、超强的伸缩性和史无前例的一致性保证。Jeff Dean 说,当一个系统增长到十倍规模时,就需要进行重新设计。那么,对于 RISE 实验室的研究员们来说,怎样才能设计出一个具备指数级增长规模的...
Saving Application State in Node.js How can I save the application state for a node.js Application that consists mostly of HTTP request? I have a script in Node.JS th...
Socket.IO on subdomains with Express.js vhost I have two Express.js apps running on my server. A plain vanilla app called "main-app" and another that uses Socket.IO called "socket-app". I ...
“阿里人”分享大型网站架构系列:缓存在分布式系统中的应用... 分布式缓存 CDN,反向代理缓存,主要解决静态文件,或用户请求资源的缓存,数据源一般为静态文件或动态生成的文件(有缓存头标识)。 分布式缓存,主要指缓存用户经常访问数据的缓存,数据源为数据库。一般起到热点数据访问和减轻数据库压力的作用。 目前分布式缓存设计,在大型网站架构中是必备的架构要...
Node.js Recipes - The solution to all Node problems责编内容来自:Node.js Recipes - The solution to all Node problems (源链) | 更多关于

阅读提示:酷辣虫无法对本内容的真实性提供任何保证,请自行验证并承担相关的风险与后果!
本站遵循[CC BY-NC-SA 4.0]。如您有版权、意见投诉等问题,请通过eMail联系我们处理。
酷辣虫 » How can I have different web browsers subscribe to separate channels in a Redis/Node.js/Soc…



专业 x 专注 x 聚合 x 分享 CC BY-NC-SA 4.0

使用声明 | 英豪名录