Skip to main content

如何断开特定客户端

¥How to disconnect a specific client

独立式

¥Standalone

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

集群

¥Cluster

无确认

¥Without acknowledgement

function disconnectSocket(id) {
io.in(id).disconnectSockets();
}

参考:server.disconnectSockets([close])

¥Reference: server.disconnectSockets([close])

tip

此方法还可用于断开给定用户的连接:

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

function computeUserId(socket) {
// to be implemented
}

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

function disconnectUser(userId) {
io.in(userId).disconnectSockets();
}

有确认

¥With acknowledgement

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

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

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

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

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

< 返回示例列表

¥< Back to the list of examples