Skip to content

Commit 9932313

Browse files
authored
Update Hibernation Websocket Example (#25971)
This updates the example in several ways: - Update the message contents so they are not the same in all cases. - Remove closing WS connections from the sessions map
1 parent 3f2894d commit 9932313

File tree

1 file changed

+4
-3
lines changed

1 file changed

+4
-3
lines changed

src/content/docs/durable-objects/examples/websocket-hibernation-server.mdx

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -131,24 +131,25 @@ export class WebSocketHibernationServer extends DurableObject {
131131

132132
// Upon receiving a message from the client, the server replies with the same message, the session ID of the connection,
133133
// and the total number of connections with the "[Durable Object]: " prefix
134-
ws.send(`[Durable Object] message: ${message}, from: ${session.id}. Total connections: ${this.sessions.size}`);
134+
ws.send(`[Durable Object] message: ${message}, from: ${session.id}, to: the initiating client. Total connections: ${this.sessions.size}`);
135135

136136
// Send a message to all WebSocket connections, loop over all the connected WebSockets.
137137
this.sessions.forEach((attachment, connectedWs) => {
138-
connectedWs.send(`[Durable Object] message: ${message}, from: ${session.id}. Total connections: ${this.sessions.size}`);
138+
connectedWs.send(`[Durable Object] message: ${message}, from: ${session.id}, to: all clients. Total connections: ${this.sessions.size}`);
139139
});
140140

141141
// Send a message to all WebSocket connections except the connection (ws),
142142
// loop over all the connected WebSockets and filter out the connection (ws).
143143
this.sessions.forEach((attachment, connectedWs) => {
144144
if (connectedWs !== ws) {
145-
connectedWs.send(`[Durable Object] message: ${message}, from: ${session.id}. Total connections: ${this.sessions.size}`);
145+
connectedWs.send(`[Durable Object] message: ${message}, from: ${session.id}, to: all clients except the initiating client. Total connections: ${this.sessions.size}`);
146146
}
147147
});
148148
}
149149

150150
async webSocketClose(ws: WebSocket, code: number, reason: string, wasClean: boolean) {
151151
// If the client closes the connection, the runtime will invoke the webSocketClose() handler.
152+
this.sessions.delete(ws);
152153
ws.close(code, 'Durable Object is closing WebSocket');
153154
}
154155
}

0 commit comments

Comments
 (0)