我需要向我的应用程序 (Ruby On Rails) 添加实时性,因此,我认为更好的方法是使用 node.js + socket.io + redis。
我在后端 (node.js) 中有这个 application.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);
和前端的messages.js
var socket = io.connect('http://localhost:5001/socket.io');
socket.on('rt-change', function (data) {
console.log(data);
});
我正在使用 node application.js 命令启动 application.js,它工作正常!
MacBook-Pro-Zhirayr:rt zhirayr$ node application.js info - socket.io started
但是当我尝试从 Rails 应用程序使用 redis ($redis.publish 'rt-change', {hello:'world'}) 发送消息时,我的浏览器不会在控制台中记录任何内容。 我敢肯定,来自浏览器的连接已建立,因为当我停止 Node 时,它会抛出连接被拒绝的错误。而且我确定 redis 和 Node 之间的连接已建立,导致 application.js 中的 console.log(message) 记录了它。 但是浏览器中的 console.log 不记录任何内容。
有什么想法吗?
谢谢。
#Antoine 更新
在 application.js 中添加了 console.log io.on('连接',函数(套接字){ redis.on('消息', 函数( channel , 消息) { console.log('来自redis的新消息'); socket.emit('rt-change', 消息); }); });
当 r.publish 'rt-change', {:hello=>'world'} 被执行时,node 记录如下:
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
很奇怪, Node 为 1 条消息记录了 11 次。
请您参考如下方法:
var socket = io.connect('http://localhost:5001/socket.io');
socket.on('rt-change', function (data) {
console.log(data);
});
根据 http://socket.io 上的文档,这部分代码似乎不正确, 你应该这样做:
<script src="http://localhost:5001/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost:5001');
</script>