如何在nodejs服务器断开连接时清除redis数据库?

时间:2018-01-12 06:56:19

标签: node.js express redis socket.io event-handling

我有一个使用节点快速服务器的简单聊天室应用程序。 这使用redis数据库连接来存储已连接客户端的昵称。

当服务器关闭/断开连接时,我需要清除名为members的昵称的redis SET。 这可以通过以下方式完成:

redisClient.del("members", function(err, reply){
    console.log("members set delete :" + reply);
});

但是我应该把这段代码放在哪里?如何在服务器端断开连接时从服务器处理最终事件?

服务器代码 - chatroom.js

var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
var redis = require('redis');
var redisClient = redis.createClient();

io.on('connection', function(client){
    console.log("client connected...");
});

io.on('connection', function(client){
    client.on('join', function(name){
        client.nickname = name;
        //adding names
        client.broadcast.emit("add member", name);
        redisClient.smembers('members', function(err, names) {
            names.forEach(function(name){   
                client.emit('add member', name);    
            }); 
        });
        client.emit('add member', client.nickname)
        redisClient.sadd("members", name);
    });

    // remove clients on disconnect
    client.on('disconnect', function(name){
        client.broadcast.emit("remove member", client.nickname);
        redisClient.srem("members", client.nickname);   
    });
});

app.get('/', function(req, res){
    res.sendFile(__dirname + '/views/index.html');
});
server.listen(8080);

客户端代码 - views / index.html

<html>
    <head>
        <title>Socket.io Client</title>
        <script src="/socket.io/socket.io.js"></script>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
    </head>
    <body>
        <h2>Chat box</h2><br>
        <h4 id="status"></h4><br>
        <div>
            <h3>Active members</h3>
            <ul id="members"></ul>
        </div>

        <script>
            var socket = io.connect('http://localhost:8080');

            socket.on('connect', function(data){
                nickname = prompt("What is your nickname?");
                $('#status').html('Connected to Chat Room as \''+nickname+'\'.');        
                socket.emit('join', nickname);
            });

            socket.on('add member', function(name) {
                var member = $('<li>'+name+'</li>').data('name', name);
                $('#members').append(member);   
            });

            socket.on('remove member', function(name) {
                $('#members li').filter(function() { return $.text([this]) === name; }).remove();   
            });

            socket.on('disconnect', function(data){
                $('#status').html('Chatroom Server Down!');        
            });
        </script>
    </body>
</html>
  

如何在nodejs服务器断开连接时清除redis数据库集?

2 个答案:

答案 0 :(得分:1)

您可以在redisclient上使用错误结束事件,请查看Redis Package Documentation

undefined local variable or method `vars' for #<Rails::Generator::Commands::Create:0x00000001ca2578>

但是,由于您的连接已关闭,因此每次首次连接到redis时删除更为健康。也可以在重新连接状态下进行。

答案 1 :(得分:1)

当socket.io连接死亡时,会触发名为disconnect的事件。将重置逻辑注册到该回调。

io.sockets.on('connection', function (socket) {
  socket.on('disconnect', function () {
    redisClient.del("members", function(err, reply){
    console.log("members set delete :" + reply);
    });
  });
});

致谢:How can i handle Close event in Socket.io?