如何在ioredis中检测断开连接的用户

时间:2016-06-30 10:08:07

标签: socket.io ioredis

我是socket.io和ioredis的新手。这段代码运行正常。但我仍然无法找到一种方法来检测断开连接的用户(当用户关闭标签时)并向所有客户显示在线用户。

redis.subscribe("users");
redis.on("message",function(channel,message){
    console.log('Receive message %s from channel %s', message, channel);
    io.emit(channel,message);
    io.on("disconnect",function(socket){
        console.log("a user disconnected");
    });
});

任何帮助将不胜感激。

针对socket.io-redis

进行了更新
var io = require('socket.io')(server);
var redis = require('socket.io-redis');
io.adapter(redis({ host: '127.0.0.1', port: 6379 }));

io.sockets.on('connection', function(socket) {
  var current_user = {};
  socket.on('message', function(data) {
    current_user = json.Parse(data);
    socket.broadcast.emit('message', data);
  });

  socket.on('disconnect', function () {
    console.log(current_user); // Now I know which user is disconnected ? 
    io.emit("dc_user",current_user);
  });
});

这是告知其他客户断开哪个用户的好方法吗?

1 个答案:

答案 0 :(得分:1)

尝试使用socket.io-redis适配器:

var io = require('socket.io')(server);
var redis = require('socket.io-redis');
io.adapter(redis({ host: '127.0.0.1', port: 6379 }));

io.sockets.on('connection', function(socket) {

  socket.on('message', function(data) {
    socket.broadcast.emit('message', data);
  });

  socket.on('disconnect', function () {
    io.emit('user disconnected');
  });


});