19

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,

Rifton007
  • 291
  • 1
  • 5
  • 24

2 Answers2

26

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');
    });
    
Dries Cleymans
  • 770
  • 8
  • 20
  • 1
    If I ran multiple sockeio nodejs server in different machine, will this adaptor allow me to join selected users, from different servers, in a single room? – Aedric Dec 04 '19 at 02:53
  • 1
    @Aedric yes it will! The room itself is persisted on Redis so when you ask for users, you don't actually ask it from the server (in-memory), but from Redis (persisted across servers). From the package's GitHub page - "Adapter to enable broadcasting of events to multiple separate socket.io server nodes." – kano Mar 27 '20 at 08:17
  • Thanks a lot. Why nobody tell that we need a redis server? Accutally there are a lot of people just starting who never heard about redis that really can't understand this necessity. Again, thanks a lot – Leonardo Rick Feb 28 '21 at 23:02
  • @kano From the Github page - Note: no data is stored in Redis itself. Redis server only acts as a pub/sub server. Each emitted message is published to redis which is broadcast to other socket servers as well. – zahlen Mar 01 '21 at 09:13
-2
io.on('connect', socket => {
    socket.on("createNotifications", () => {
        io.sockets.emit("notificationCreated", {
            'id': Date.now(),
            'name': `You just created notification at date`
        });
    });
});