Home > other >  Read message from web socket with JavaScript
Read message from web socket with JavaScript

Time:11-09

I have a web page where I receive a messages from web socket:

useEffect(() => {
            let feedAddress = "ws://.../ws_endpoint";
            
            const feedClient = new W3CWebSocket(feedAddress);
            props.onUpdateWebsocket(feedClient);
            feedClient.onopen = () => {
                console.log("WebSocket Client Connected on "   feedAddress);
            };
            feedClient.onmessage = (message) => {
                let payload = JSON.parse(message.data);
                
                // parse here the response message

            };
        }, []);

I can have 2 types of messages:

success:

{
     "requestId" : <string>,
     "response" : {
         "exchange": <string>,
         "messageId" : <string>
     }
}

error:

response: {
   "errorMessage" : <string>,
   "errorCode" : <int>
}

How I can parse both types of messages and display warning messages with the both types of responses as dialog messages?

CodePudding user response:

Check for the existence of errorCode response.errorCode and conditionally process the response, since you know the structure of the responses.

Otherwise use a for...in... loop to recursively look for the string including "message" within the response object. Example on this here

CodePudding user response:

I suggest using another method to catch the error case. You can do that with onerror event:

According to the MDN documentation:

The WebSocket interface's onerror event handler property is a function that gets called when an error occurs on the WebSocket.

useEffect(() => {
    let feedAddress = "ws://.../ws_endpoint";
    
    const feedClient = new W3CWebSocket(feedAddress);
    props.onUpdateWebsocket(feedClient);
    feedClient.onopen = () => {
        console.log("WebSocket Client Connected on "   feedAddress);
    };
    
    feedClient.onmessage = (message) => {
        let payload = JSON.parse(message.data);
        // do proper action on success case
    };
    
    feedClient.onerror = (error) => {
      console.log(error)
      // do proper action on failure case
    }
}, []);
  • Related