websocket 如何在Deno中读取Blob?

wz1wpwve  于 2023-10-20  发布在  其他
关注(0)|答案(1)|浏览(136)

我正在尝试从Deno中的WebSocket读取数据。下面是代码(您需要AISstream中的API密钥才能使其工作)

/**
 * URL used by the API; this might change if the version changes or at any time, since it's experimental
 */
const AIS_API_URL = "wss://stream.aisstream.io/v0/stream";

export const defaultBoundingBox = [
  [
    [-90, -180],
    [90, 180],
  ],
];

let socket = null;

// Creates a deno websocket client and subscribes to the AIS API
export function createSocket(apiKey, boundingBoxes = defaultBoundingBox) {
  if (socket) {
    return socket;
  }
  socket = new WebSocket(AIS_API_URL);

  socket.onopen = () => {
    console.log("Socket connected");
    socket.send(
      JSON.stringify({
        apiKey,
        boundingBoxes,
      })
    );
  };

  socket.onmessage = (event) => {
    const reader = new FileReader();
    console.log(event);
    const decodedBlob = reader.readAsText(event.data);
    console.log(decodedBlob);
  };

  socket.onclose = () => {
    console.log("Socket closed");
  };
  return socket;
}

问题出在on message上。成功接收消息/事件。但是dataBlob中。我尝试使用TextDecoderreadAsText解码它。但是,这将返回undefined
在这里使用JS是没有问题的:event.data作为字符串返回,然后可以解析为JSON。不过,我想不通。

9w11ddsr

9w11ddsr1#

为了将Blob的内容读取为文本,可以使用.text()方法。

socket.onmessage = async(event) => {
  const decodedBlob = await event.data.text();
  console.log(decodedBlob);
  const data = JSON.parse(decodedBlob);
};

您也可以像以前那样使用FileReader,但是您错过了FileReader.onload侦听器

socket.onmessage = (event) => {
  const reader = new FileReader();
  reader.onload = () => {
    const decodedBlob = reader.result;
    console.log(decodedBlob);
  };
  reader.readAsText(event.data); // does not return the data
};

相关问题