Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 7a680d8

Browse files
committedMar 28, 2025··
docs: how to disconnect a specific client
Related: socketio/socket.io-redis-streams-adapter#30
1 parent 6217ebc commit 7a680d8

File tree

2 files changed

+76
-0
lines changed

2 files changed

+76
-0
lines changed
 

‎src/pages/get-started/index.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,3 +46,4 @@ If you are new to Socket.IO, we recommend checking out our [tutorial](/docs/v4/t
4646
- [get the IP address of the client](/how-to/get-the-ip-address-of-the-client)
4747
- [count the number of connected clients](/how-to/count-connected-clients)
4848
- [count the number of connected users](/how-to/count-connected-users)
49+
- [disconnect a specific client](/how-to/disconnect-a-specific-client)
Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
---
2+
title: How to disconnect a specific client
3+
---
4+
5+
# How to disconnect a specific client
6+
7+
## Standalone
8+
9+
```js
10+
function disconnectSocket(id) {
11+
io.of("/").sockets.get(id)?.disconnect();
12+
}
13+
```
14+
15+
## Cluster
16+
17+
### Without acknowledgement
18+
19+
```js
20+
function disconnectSocket(id) {
21+
io.in(id).disconnectSockets();
22+
}
23+
```
24+
25+
Reference: [`server.disconnectSockets([close])`](/docs/v4/server-api/#serverdisconnectsocketsclose)
26+
27+
:::tip
28+
29+
This method can also be used to disconnect a given user:
30+
31+
```js
32+
function computeUserId(socket) {
33+
// to be implemented
34+
}
35+
36+
io.on("connection", (socket) => {
37+
const userId = computeUserId(socket);
38+
socket.join(userId); // use a room named after the user ID
39+
});
40+
41+
function disconnectUser(userId) {
42+
io.in(userId).disconnectSockets();
43+
}
44+
```
45+
46+
:::
47+
48+
### With acknowledgement
49+
50+
```js
51+
function disconnectLocalSocket(id) {
52+
return io.of("/").sockets.get(id)?.disconnect() !== undefined;
53+
}
54+
55+
io.on("disconnectSocket", (id, cb) => {
56+
cb(disconnectLocalSocket(id));
57+
});
58+
59+
async function disconnectSocket(id) {
60+
if (disconnectLocalSocket(id)) {
61+
return true;
62+
}
63+
try {
64+
const res = await io.serverSideEmitWithAck("disconnectSocket", id);
65+
return res.some(v => v);
66+
} catch (e) {
67+
// something went wrong
68+
}
69+
}
70+
```
71+
72+
Reference: [`server.serverSideEmitWithAck(eventName[, ...args]);`](/docs/v4/server-api/#serverserversideemitwithackeventname-args)
73+
74+
75+
[< Back to the list of examples](/get-started/)

0 commit comments

Comments
 (0)
Please sign in to comment.