处理浏览器刷新socket.io

时间:2015-03-08 18:58:13

标签: socket.io

我有一个要求使用节点js来处理用户与聊天应用程序的连接。

我不知道如何处理浏览器关闭和用户刷新浏览器之间的区别。

client.on('disconnect', function () {
        console.log( 'Disconnected' );
        // run mysql code to remove user from logged in table
});

我用Google搜索了几个小时,无法找到解决方案。

这看起来很简单,我认为这是我正在使用的关键字。

有人能指出我如何处理这个问题的正确方向吗?

提前致谢。

2 个答案:

答案 0 :(得分:3)

一种方法是生成随机UID并将其保存到本地存储。在客户端连接之后,将此UID发送到服务器并检查该UID是否作为连接用户存在。在服务器端,在断开连接中设置超时,在从“用户在线”数据中删除其唯一UID之前,用户需要15秒左右。

<强>客户端:

// When the client starts, create the uid.
localstorage.setItem('uUID', Math.random().toString(24) + new Date());

// Emit the UID right after connection
socket.emit('userLogin', localstorage.getItem('uUID');

服务器

var currentUIDS = [];
var userIsConnected = true;


io.sockets.on('connection', function (socket) {
    var currentUID = null;

    socket.on('userLogin', function (data) {
        if (data !== null) {
            if (currentUIDS.includes(data)) {
                userIsConnected = true;
        currentUID = data;
            }
        }
    });

    socket.on('disconnect', function () {
        userIsConnected = false;
        setTimeout(function () {
            if (!userIsConnected) currentUIDS.pop(currentUID);
        }, 15000);
    });
});

答案 1 :(得分:2)

我有一个更好的解决方案来处理多个用户:

var users = [],
    users_connected = [];

io.on('connection', function(socket) {
  var uid = null;

  // register the new user
  socket.on('register', function (user_uid) {
    if ( users_connected.indexOf(user_uid) < 0 ) {
      users_connected.push(user_uid);
    }

    if ( users.indexOf(user_uid) < 0 ) {
      console.log('New user connected: ' + user_uid);
      users.push(user_uid);

      // notify other clients that a new user has joined
      socket.broadcast.emit('user:join', {
        name: user_uid,
        users: users_connected.length
      });
    }

    uid = user_uid;
  });

  // clean up when a user leaves, and broadcast it to other users
  socket.on('disconnect', function () {
    users_connected.splice( users_connected.indexOf(uid), 1);

    setTimeout(function () {
      if ( users_connected.indexOf(uid) < 0 ) {
        socket.broadcast.emit('user:left', {
          name: uid
        });

        var index = users.indexOf(uid);
        users.splice(index, 1);
      }
    }, 3000);
  });

});