Pay attention to the data format expected by the server and deserialize incoming payloads according to their type.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 const ws = new WebSocket ('wss://example.com/socket' );ws.binaryType = 'arraybuffer' ; ws.onopen = () => { console .log ('Connected' ); ws.send (JSON .stringify ({ Version : { Version : 'v0.0.1' } })); }; ws.onmessage = async event => { if (typeof event.data === 'string' ) { console .log ('Received string data:' , event.data ); const value = JSON .parse (event.data ); console .log (value); return ; } let arrayBuffer : ArrayBuffer ; if (event.data instanceof ArrayBuffer ) { arrayBuffer = event.data ; } else if (event.data instanceof Blob ) { arrayBuffer = await event.data .arrayBuffer (); } else { console .log ('Received an unknown data type:' , event.data ); return ; } const bytes = new Uint8Array (arrayBuffer); const jsonString = new TextDecoder ().decode (bytes); const value = JSON .parse (jsonString); console .log (value); }; ws.onerror = error => { console .error ('WebSocket error:' , error); }; ws.onclose = event => { console .log (`WebSocket closed: ${event.code} ${event.reason} ` ); };
In production, validate parsed messages, catch malformed JSON, use wss://, authenticate the connection, and implement an appropriate reconnect strategy.