![](/img/trans.png)
[英]How can I detect when a Socket.IO emit() was sent but not received by any .on() handler?
[英]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')
})
})
解釋:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.