使用socket.io-redis的示例

Rif*_*007 4 redis socket.io socket.io-redis

大家好,感谢您的宝贵时间和帮助。

我需要一个使用socket.io-redis的简单示例,请提供注释。我阅读了文档,但听不懂。谢谢,

Dri*_*ans 6

socket.io-redis文档没有提到您实际上需要运行redis服务器,因此您可能已经忘记了这一点。socket.io-redis插件使用redis服务器的pub / sub客户端连接多个socket.io实例。

  1. https://redis.io下载并安装Redis服务器

  2. 将redis插件添加到您的socket.io实例中:

    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 }));
    
    Run Code Online (Sandbox Code Playgroud)

    6379是默认的redis端口,如果在同一服务器上运行node和redis,则为localhost。

  3. 添加您需要的socket.io和socket.io-redis函数

    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);
        });
      });
    });
    
    Run Code Online (Sandbox Code Playgroud)
  4. 使用socket.io启动服务器

    server.listen(3000, function(){
       logger.debug('listening on *:3000');
    });
    
    Run Code Online (Sandbox Code Playgroud)