簡體   English   中英

如何檢測 socket.io 上的斷開連接?

[英]How can I detect disconnects on socket.io?

我在我的項目中使用 socket.io。 我打開了重新連接功能。 如果用戶與服務器斷開連接,我想顯示警報(您的互聯網連接丟失。嘗試重新連接)。 如果用戶再次重新連接,我想再顯示一個警報(別擔心,您已連接)。

我該怎么做?

要在您使用的客戶端上進行檢測

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

它與node.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
});

我這樣處理這個問題。 我在客戶端上發了一個發送發送器,它在服務器上調用heartbeat。

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();

受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. a:如果響應在 4 秒內出現,則取消 4 秒定時器並刷新 60 秒定時器(重新啟動進程)
  5. b:如果響應失敗或延遲太多,則調用 disconnect() function

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM