I am using javascript and the ws package in expressjs to build my server.
I'm building a chat application for my portfolio and originally my idea was to have the client tell the server which chats the user is in (subscriptions) and store them in a subscriptions
array.
for (let i = 0; i < subscriptions.length; i++) { wss.clients.forEach((client) => { if (json.body.chatId === subscriptions[0][i]){ client.send(message) } }) }
This is the approach I want, but the message is sent to every connected client, which is too bad.
The subscriptions object is just an array containing the IDs of the chats the user is in.
How to send messages only to clients in chat?
First, you need to maintain a method that maps each client to the chat ID to which it is subscribed. You can do this using JavaScript's
Map
, where the keys are client objects and the values are an array of chat IDs they are subscribed to:When a client connects to WebSocket, store its subscription information in subscriptionsMap. When clients disconnect, make sure to remove their subscriptions from the map:
Now when you receive a message that needs to be sent to a client in a specific chat, iterate through the connected clients and only send the message to those clients subscribed to the relevant chat ID: