How to send a message to another socket.io server using socket.io-redis?

I need two different socket.io servers to communicate with each other. I can't use socket.io-client

as it doesn't distinguish between connections browser to server

and server to server

. So I am trying to use socket.io-redis

.

One is the express-socket.io server and the other is the standalone socket.io server. Both were configured to use an adapter socket.io-redis

. I cannot see the message received on Server1 from Server2. Also there are no errors.

Server1:

var express = require('express');
var app = express();

var server = app.listen(8000,function () {
	console.log('server listening at port 8000');
});

var io = require('socket.io')(server);
var redis = require('socket.io-redis');
io.adapter(redis({ host: 'localhost', port: 6379 }));

io.on('message',function (message) {
	console.log(message);
});

io.on('connection',function (socket) {
	console.log('connection');
	socket.on('message',function (message) {
		console.log(message);
	});
});
      

Run code


Server2:

var io = require('socket.io')(3000);
var redis = require('socket.io-redis');
io.adapter(redis({ host: 'localhost', port: 6379 }));

io.emit('message','Hi');
      

Run code


+3


source to share


1 answer


socket.io-redis will not let you write events from one server to another. The way it works is simply to "push" messages sent by one server to other connected servers, so they can relay those messages.

If instance A receives an event (i.e. io.on('connect')

), you will not be able to capture that event on instance B. However, you will be able to send a message to all clients connected to all instances by simply calling

socket.on('message', function(socket){
   socket.emit('hello', 'New message');
}

      

This way, you will broadcast the message to all clients connected to instance A or B (including yourself). This approach allows you to scale your application to other instances on the same machine (use more than one thread) or to different servers.



If you need your servers to "talk" to each other, you can use your existing transport layer, the Express Server. You can create handlers for different types of requests, for example:

app.get('/api/clientCount', function(req, res){
  res.send(io.engine.clientsCount);
});

      

This way. You can exchange information between socket.io instances, change their state, make all report instances, etc. Remember - authenticate requests; You don't want to receive these calls from unauthorized users :)

+3


source







All Articles