Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

not receiving events with this basic socket.io + redis setup?

I've got a simple socket.io server using socket.io-redis, an socket.io-emitter, and I run redis (which is completely new to me, I'm on windows, I downloaded redis and opened redis-server.exe and redis-cli.exe). Through the redis CLI with the command monitor I see that the server is connected and that events reach redis from the emitter, but test-server.js never logs anything. What else do I need to do? Does the socket.io server need to subscribe to redis?

Redis output "publish" "socket.io#/#" "\x93\xa7emitter\x83\xa4type\x02\xa4data\x92\xa4test\xa9some data\xa3nsp\xa1/\x82\xa5rooms\x90\xa5flags\x80"

test-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);

test-emit.js

var io = require('socket.io-emitter')({
    host:'localhost',
    port:'6379'
});
setInterval(function(){
    io.emit('test', 'some data');
    console.log('emitted');
}, 5000);
like image 717
Flion Avatar asked Jul 12 '16 14:07

Flion


1 Answers

the answer is that socket.io-emitter was not what I needed for this test case. It connects directly to redis. In the example below I now use the usual socket.io-client and all events properly arrive in the server, and also with two servers and two clients connected each to a different server, with io.emit both clients now recieve the event. Great!

test-emit.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);
    });
});

test-server.js

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);
    });
});

start 4 different terminals and run:

$ node test-server 3000
$ node test-server 3001
$ node test-emit 3000
$ node test-emit 3001
like image 87
Flion Avatar answered Sep 30 '22 00:09

Flion