To convert a WebSocket's BinaryMessage to a String, you need to use the TextDecoder object. TextDecoder is a built-in object that decodes a sequence of bytes into a string.

Here's an example code snippet demonstrating the conversion from WebSocket's BinaryMessage to String:

// Create a TextDecoder object
const decoder = new TextDecoder();

// Listen for the WebSocket's BinaryMessage event
socket.addEventListener('message', event => {
  if (event.data instanceof Blob) {
    const reader = new FileReader();
    reader.addEventListener('loadend', () => {
      // Decode the byte sequence into a string
      const text = decoder.decode(reader.result);
      console.log(text);
    });
    reader.readAsArrayBuffer(event.data);
  }
});

In the above code snippet, we first create a TextDecoder object. Then, we check if the message is a Blob object in the WebSocket's BinaryMessage event. If it is, we use the FileReader object to read the Blob object as a byte array. Finally, we use the TextDecoder object to decode the byte array into a string.

WebSocket BinaryMessage to String Conversion in JavaScript

原文地址: https://www.cveoy.top/t/topic/mzJB 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录