I need to add realtime to my application (Ruby On Rails), so, I think that the better way to do it is to use node.js + socket.io + redis.
I have this application.js file in a backend (node.js)
var app = require('http').createServer();
var io = require('socket.io');
var redis = require('redis').createClient();
var _ = require('underscore')._;
io = io.listen(app);
io.configure(function() {
io.set("transports", ["xhr-polling"]);
io.set("polling duration", 10);
io.set("close timeout", 10);
io.set("log level", 1);
})
redis.subscribe('rt-change');
io.on('connection', function(socket) {
redis.on('message', function(channel, message) {
socket.emit('rt-change', message)
});
});
var port = process.env.PORT || 5001;
app.listen(port);
And messages.js in frontend
var socket = io.connect('http://localhost:5001/socket.io');
socket.on('rt-change', function (data) {
console.log(data);
});
I'm launching application.js with node application.js command and it works!
MacBook-Pro-Zhirayr:rt zhirayr$ node application.js info - socket.io started
But when I'm trying to send message with redis ($redis.publish 'rt-change', {hello:'world'}) from Rails application, my browser doesn't log anything in console. I'm sure, that connection from browser established, cause when I stop node, it throws connection refused error. And I'm sure that connection between redis and node established, cause console.log(message) in application.js logs it. But console.log in browser doesn't log anything.
Any ideas why?
Thanks.
UPD for #Antoine
Added console.log in application.js io.on('connection', function(socket) { redis.on('message', function(channel, message) { console.log('new message from redis'); socket.emit('rt-change', message); }); });
When r.publish 'rt-change', {:hello=>'world'} become executed, node logs this:
new message from redis
new message from redis
new message from redis
new message from redis
new message from redis
new message from redis
new message from redis
new message from redis
new message from redis
new message from redis
new message from redis
It's strange, node logs 11 times for 1 message.
var socket = io.connect('http://localhost:5001/socket.io');
socket.on('rt-change', function (data) {
console.log(data);
});
This part of the code does not seem correct, according to the doc on http://socket.io , you should do something like:
<script src="http://localhost:5001/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost:5001');
</script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With