Note that there are some explanatory texts on larger screens.

plurals
  1. POHow can I have different web browsers subscribe to separate channels in a Redis/Node.js/Socket.io pub/sub setup?
    primarykey
    data
    text
    <p>I'd like different clients (web browsers) to be able to subscribe to separate Redis channels.</p> <p>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.</p> <p>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".</p> <p><strong>client1.html</strong></p> <pre><code>&lt;script src="/socket.io/socket.io.js"&gt;&lt;/script&gt; &lt;script&gt; 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); }); &lt;/script&gt; </code></pre> <p>Here is the Node.js file.</p> <p><strong>app.js</strong></p> <pre><code>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'); </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload