Example to use socket.io-redis
Asked Answered
S

2

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,

Stela answered 9/7, 2016 at 14:17 Comment(0)
P
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');
    });
    
Pratt answered 3/8, 2017 at 7:8 Comment(4)
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?Dewaynedewberry
@Dewaynedewberry 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."Melvinamelvyn
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 lotCrossbow
@Melvinamelvyn 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.Ingesta
M
-2
io.on('connect', socket => {
    socket.on("createNotifications", () => {
        io.sockets.emit("notificationCreated", {
            'id': Date.now(),
            'name': `You just created notification at date`
        });
    });
});
Mickens answered 6/6, 2022 at 12:39 Comment(2)
please covert this code into socket.io-redisMickens
I'm not sure how this answer's OP's question.Whitelaw

© 2022 - 2024 — McMap. All rights reserved.