How to send a WebSocket message conditionally?
P粉933003350
P粉933003350 2023-09-18 14:56:33
0
1
646

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?

P粉933003350
P粉933003350

reply all(1)
P粉198749929

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:

const subscriptionsMap = new Map();

When a client connects to WebSocket, store its subscription information in subscriptionsMap. When clients disconnect, make sure to remove their subscriptions from the map:

wss.on('connection', (client) => {
  // 处理客户端连接

  // 假设`json.body.subscriptions`包含客户端订阅的聊天ID数组
  subscriptionsMap.set(client, json.body.subscriptions);

  // 处理客户端断开连接
  client.on('close', () => {
    subscriptionsMap.delete(client);
    // 执行任何必要的清理操作
  });
});

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:

// 假设`json.body.chatId`包含消息的聊天ID
const chatId = json.body.chatId;

wss.clients.forEach((client) => {
  if (subscriptionsMap.has(client) && subscriptionsMap.get(client).includes(chatId)) {
    client.send(message);
  }
});
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template