redissocket.iosocket.io-redis

Example to use socket.io-redis


Hi all and thanks for your time and your help.

I need a simple example for use socket.io-redis, with comments please. I read the documentation, but I did not understand. Thank you,


Solution

  • The socket.io-redis documentation don't mention you actually need to run a redis server so you might have forgotten that. The socket.io-redis plugin uses the pub/sub client of the redis server to connect multiple socket.io instances.

    1. download and install a redis server from https://redis.io

    2. add the redis plugin to your socket.io instances:

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

      The 6379 is the default redis port, localhost if you run node and redis on the same server.

    3. add socket.io and socket.io-redis functions you need

      var your_namespace_socket = io.of('/your-namespace');
      your_namespace_socket.on('connection', function(socket){
      
        socket.on('join', function(room){
          socket.join(room);
      
          //log other socket.io-id's in the room
          your_namespace_socket.adapter.clients([room], (err, clients) => {
            console.log(clients);
          });
        });
      });
      
    4. Start the server with socket.io

      server.listen(3000, function(){
         logger.debug('listening on *:3000');
      });