admin管理员组

文章数量:1422062

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.

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.

Share Improve this question asked Jan 17 at 15:44 Lucky Govind raoLucky Govind rao 91 bronze badge 1
  • What is WebSocketClient? A library or your own code? Does your own code or library code handle the tag and uid separation from websocket messages? – cbr Commented Jan 17 at 16:23
Add a comment  | 

1 Answer 1

Reset to default 0

This is a pretty simple change really.

Instead of this:

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
     });

Put the websocket in a global variable

window.ws = new WebSocketClient(...);

This way you can send out messages from any function.

I also recommend setting up a WebSocket message protocol, so that you can send multiple kinds of messages. You can do this in JSON or XML, like

{
  type: 1,
  content: ...;
}

This way, when messages come in, you can route them to the right message handler.

本文标签: javascriptHow to loop over tags and messages while maintaining a single WebSocket connectionStack Overflow