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
anduid
s and process their corresponding messagesIssue
When I attempt to connect to the WebSocket URL only once and loop over the
tags
,uid
, andmessages
, it doesn’t work as expected. Eachtag
needs its own uniqueuid
and message processing, but I want to avoid opening multiple WebSocket connections.What I’ve Tried
-
Creating one
wsClient
and looping through thetags
, but I couldn’t find a way to associate theuid
andtag
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 ownuid
?Any suggestions or best practices for handling this scenario would be appreciated.
-