Ir para o conteúdo principal
Latest blog post (July 25, 2024): npm package provenance.

How to disconnect a specific client

Standalone

functiondisconnectSocket(id){
io.of("/").sockets.get(id)?.disconnect();
}

Cluster

Without acknowledgement

functiondisconnectSocket(id){
io.in(id).disconnectSockets();
}

Reference: server.disconnectSockets([close])

tip

This method can also be used to disconnect a given user:

functioncomputeUserId(socket){
// to be implemented
}

io.on("connection",(socket)=>{
const userId =computeUserId(socket);
socket.join(userId);// use a room named after the user ID
});

functiondisconnectUser(userId){
io.in(userId).disconnectSockets();
}

With acknowledgement

functiondisconnectLocalSocket(id){
return io.of("/").sockets.get(id)?.disconnect()!==undefined;
}

io.on("disconnectSocket",(id, cb)=>{
cb(disconnectLocalSocket(id));
});

asyncfunctiondisconnectSocket(id){
if(disconnectLocalSocket(id)){
returntrue;
}
try{
const res =await io.serverSideEmitWithAck("disconnectSocket", id);
return res.some(v=> v);
}catch(e){
// something went wrong
}
}

Reference: server.serverSideEmitWithAck(eventName[, ...args]);

< Back to the list of examples

AltStyle によって変換されたページ (->オリジナル) /