Close Multiple WebSocket Clients with MSW

Event handlers in MSW represent a WebSocket server. And it so happened a single server may manage a communication across multiple clients. Let's see how we can close multiple WebSocket client connections at once!

We can get access to the set of all connected WebSocket clients in the chat.clients property. From then, it's a matter of iterating over them and calling client.close() on individual clients.

Resources

Share with a coworker

Social Share Links

Transcript

[00:00] Using client.close() is really great if you want to close a particular WebSocket client. Like here, if I type close() in the chat, this client will disconnect. However, a different tab of the same application will have a different client instance, so this will still remain open. To close multiple WebSocket clients you need to get the reference to all those clients. You can do so if you access our WebSocket link, the chat object, and its clients property.

[00:27] This is going to be a set of all the intercepted WebSocket clients that match this WebSocket link. So here we can do for each, get access to each individual client, and call its client.close() method. Let's make this logic conditional so it only happens when a particular message has been set in the chat. Let's make it an uppercase stop message. Move this logic inside the if statement and do an early return.

[00:52] Now if any of the clients sends this stop message it will disconnect but it will also disconnect any other clients even if they're in a different tab.