我有一个简单的socket.io服务器使用socket.io-redis,一个socket.io-emitter,我运行redis(这对我来说是全新的,我在Windows上,我下载了redis并打开了redis-server.exe和redis-cli.exe)。
通过带有命令monitor
的redis CLI,我看到服务器已连接,并且事件从发射器到达redis,但test-server.js
从不记录任何内容。我还需要做什么? socket.io服务器是否需要订阅redis?
Redis输出"publish" "socket.io#/#" "\x93\xa7emitter\x83\xa4type\x02\xa4data\x92\xa4test\xa9some data\xa3nsp\xa1/\x82\xa5rooms\x90\xa5flags\x80"
测试server.js
var server = require('http').Server();
var io = require('socket.io')(server);
var redis = require('socket.io-redis');
io.adapter(redis({ host: '127.0.0.1', port: 6379 }));
io.on('connection', function(socket){
console.log('client connected'); // Works
socket.emit('connect','test'); // Works
});
io.on('test', function(socket){
console.log('test came in'); // Works
});
server.listen(3000);
测试emit.js
var io = require('socket.io-emitter')({
host:'localhost',
port:'6379'
});
setInterval(function(){
io.emit('test', 'some data');
console.log('emitted');
}, 5000);
答案 0 :(得分:2)
答案是using
不是我需要的测试用例。
它直接连接到redis。在下面的示例中,我现在使用通常的socket.io-emitter
,并且所有事件都正确到达服务器,并且还有两个服务器和两个客户端连接到不同的服务器,socket.io-client
两个客户端现在都收到了事件。太好了!
<强>测试emit.js 强>
io.emit
<强>测试server.js 强>
var PORT = 3000;
var HOST = 'http://localhost';
var port = parseInt(process.argv[2]) || PORT;
var io = require('socket.io-client');
var socket = io.connect(HOST + ':' + port);
socket.on('connect', function () {
console.log('connected, sending message');
socket.emit('message', 'message from client');
socket.on('message', function(data) {
console.log('new message received: '+data);
});
});
启动4个不同的终端并运行:
var port = parseInt(process.argv[2]) || 3000;
console.log('server listens on port ' + port);
var io = require('socket.io').listen(port);
var redis = require('socket.io-redis');
var adapter = redis({ host: '127.0.0.1', port: 6379 });
io.adapter(adapter);
io.on('connection', function(socket){
console.log('client connected');
io.emit('message', 'client logged in on '+port+' and this message will be send to all clients');
socket.on('message', function(d){
console.log('message from socket:',d);
});
});