简体   繁体   中英

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

I need to have two different socket.io servers communicate with each other. I cannot use socket.io-client since it does not differentiate between browser to server connections and server to server connections. So I am trying to use socket.io-redis .

One is an express-socket.io server and another is a standalone socket.io server. Both have been configured to use socket.io-redis adapter. I do not see message received at 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); }); }); 

Server2:

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

socket.io-redis will not allow You to capture events from one server on another. How it works is it will simply "push" messages emited by one server to other connected servers, so those can emit those messages to.

If instance A will recieve an event (ie. io.on('connect') ), You will not be able to capture that event on instance B. You will however be able to emit a message to all clients connected to all instances, simply by calling

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

This way You will broadcast the message to all clients, either connected to instance A or B (including Yourself for that matter). This approach allows You to scale out Your application to other instances on one machine (utilize more than one thread) or to other servers.

If You need Your servers to "talk" to each other, You can utilize Your existing transport layer - Express server. You could create handlers for different type 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 instances report usage, etc. Thing to remember - authenticate requests; You don't want to get those calls from unauthorised users :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM