我在项目中使用了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
});
disconnect
直到套接字重试超时后才会触发。 - mobbyconnect
回调函数中。该回调函数会在重新连接时触发,并逐渐注册更多的断开处理程序。 - Carcigenicatesocket.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 的启发,我也做了一个在线检查器。
服务器端
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')
})
})
说明: