Example to use socket.io-redis

做~自己de王妃 提交于 2019-12-22 08:07:30

问题


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,


回答1:


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');
    });
    


来源:https://stackoverflow.com/questions/38282742/example-to-use-socket-io-redis

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!