How to loop over tags and messages while maintaining a single WebSocket connection?

I am trying to set up WebSocket connections in a way where I only connect to the WebSocket URL once and loop over my tags, uid, and messages. However, my current implementation doesn’t work as expected.

Here is my current code:

 setupWebSockets() {
    const baseConfig = {
     url: CONFIG.WS_URL,
     ...CONFIG.WS_MESSAGE
    };

    this.tags.forEach(tag => {
     const uid =generateUID(); 
     const wsClient = new WebSocketClient(baseConfig.url, {
      ...baseConfig,
      uid,
      tag
     });
     wsClient.setOnMessageCallback((event) => this.handleWebSocketMessage(event, tag));
     wsClient.connect();
     this.wsClients[tag] = wsClient;
    });
}

handleWebSocketMessage(event, tag) {
    try {
        const receivedData = JSON.parse(event.data);
        console.log(`Received WebSocket data for ${tag}:`, receivedData);

        if (receivedData.measurements && receivedData.measurements.length > 0) {
            const formattedMeasurements = receivedData.measurements.map(measurement => ({
                time: this.wsClients[tag].convertTimestamp(measurement.time),
                value: measurement.value
            }));
            this.lineChart.updateData(formattedMeasurements, tag);
        }
    } catch (error) {
        console.error(`Error parsing received message for ${tag}:`, error);
    }
}

What I’m Trying to Achieve

  • I want to connect to the WebSocket URL (CONFIG.WS_URL) only once.

  • I need to handle multiple tags and uids and process their corresponding messages

    Issue

    When I attempt to connect to the WebSocket URL only once and loop over the tags, uid, and messages, it doesn’t work as expected. Each tag needs its own unique uid and message processing, but I want to avoid opening multiple WebSocket connections.

    What I’ve Tried

    • Creating one wsClient and looping through the tags, but I couldn’t find a way to associate the uid and tag with the incoming messages correctly.

    • Opening a WebSocket connection for each tag (as shown in the code), which works but isn’t efficient.

    Question

    How can I restructure my code to use a single WebSocket connection and efficiently handle messages for multiple tags, each with its own uid?

    Any suggestions or best practices for handling this scenario would be appreciated.