如何检测 socket.io 上的断开连接

How can I detect disconnects on socket.io?

本文关键字:io 断开 连接 socket 何检测 检测      更新时间:2023-09-26

我在项目中使用 socket.io。我打开了重新连接功能。我想如果用户与服务器断开连接,则显示警报(您的互联网连接丢失。正在尝试重新连接)。如果用户再次重新连接,我想再显示一个警报(别担心,您已连接)。

我该怎么做?

在您使用的客户端上进行检测

  // CLIENT CODE
  socket.on('disconnect', function(){
      // Do stuff (probably some jQuery)
  });

对于节点.js服务器,它与上面的代码完全相同。

如果出于某种原因,您希望检测到用户断开连接并将其显示给其他人,则需要使用服务器来检测离开的人,然后使用以下内容向其他人发送回一条消息:

socket.on('disconnect', function(){
    socket.broadcast.to(roomName).emit('user_leave', {user_name: "johnjoe123"});
});

希望这有帮助

socket.io有一个disconnect事件,把它放在你的connect块中:

socket.on('disconnect', function () {
    //do stuff
});

我是这样处理这个问题的。我在客户端上制作了一个发出发送器,该发送器正在服务器上调用心跳。

socket.on('heartbeat', function() {
        // console.log('heartbeat called!');
        hbeat[socket.id] = Date.now();
        setTimeout(function() {
            var now = Date.now();
            if (now - hbeat[socket.id] > 5000) {
                console.log('this socket id will be closed ' + socket.id);
                if (addedUser) {
                    --onlineUsers;
                    removeFromLobby(socket.id);
                    try {
                        // this is the most important part
                        io.sockets.connected[socket.id].disconnect();
                    } catch (error) {
                        console.log(error)
                    }
                }
            }
            now = null;
        }, 6000);
    });

我发现这个代码函数要调用:

io.sockets.connected[socket.id].disconnect();

inpired on invicibleTrain iv 也做了一个在线检查器

服务器端

const sockets={online:{},admins:{}}
// the disconnect function you create the way you wish to, example:
const disconnect=()=>{
  socket.emit('disconected')
  io.in(socket.id).disconnectSockets()
  delete sockets.online[socket.uid]
}
io.on('connection',socket=>{
  socket.emit('connection',socket.id)
  // the checker if user is online
  let drop
  const dropCheck=()=>{
    if(!socket) return; // if user connects twice before the check, simply stops process
    socket.emit('dropCheck')
    drop = setTimeout(()=>disconnect(),4000) // 4 secs to recieve answer
  }
  const setDrop=()=>setTimeout(()=>dropCheck(),60000) // 60 secs to restart the process
  socket.on('dropCheck',()=>{
    clearTimeout(drop) // cancells actual drop coutdown (if any)
    setDrop() // sets a new
  })
  //sets the user ID inside the socket used for comunication
  socket.on('uid',uid=>{
    socket.online[uid] = {status:'busy',socket:socket.id}
    setDrop()
  })
})

客户端

const sio = io(`...httpAddress...`,{transports:['websocket']})
sio.on('connection',socket=>{
  sio.emit('uid','user Id here..') // sends the the user ID: uid
  sio.on('dropCheck',()=>{ // responds to the checker
    sio.emit('dropCheck')
  })
})

解释:

  1. 用户登录并在 60 秒后 dropCheck 被调用
  2. dropCheck 发出 ping 并将计时器设置为 4 秒
  3. 用户处理发出的 ping 并响应另一个 ping
  4. 答:如果响应在 4 秒内出现,则 4 秒计时器将被取消并刷新 60 秒计时器(重新启动过程)
  5. b:如果响应失败或延迟太多,则调用 disconnect() 函数