【问题标题】:Make websocket receive data readable - nodejs使 websocket 接收数据可读 - nodejs
【发布时间】:2021-11-02 06:43:37
【问题描述】:

我今天刚开始学习编码,并在使用 websockets。

我正在使用 npm 包 ws 连接到 websocket 服务器,我正在尝试弄清楚我正在接收什么数据。

我以为我会收到一个 json,因为我正在向 websocket 服务器发送一个 json,但它看起来一点也不像 json。

所以我的问题是有人可以告诉我我正在接收什么数据吗?无论如何我可以让它可读吗?

我收到的数据:

{
  [Uint8Contents]: <b0 01 00 a1 71 01 00 00 01 00 00 01 32 18 a0 43 8c 8c 9d c2 df 18 12 00 00 00 00 00 00 00 00 00>,
  byteLength: 32
}

不确定这是否有助于解决我的问题,但这是我用来连接 websocket 的函数:

const WebSocket = require('ws');

const connect = (endpoint) => {
  try {
    let options = {
      headers: {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3419.0 Safari/537.36"
      }
    };

    let client = new WebSocket(endpoint, options);

    client.onopen = () => {
      console.log("websocket open");
      client.send("42" + JSON.stringify(["getRooms", false]));
    };

    client.onmessage = (event) => {
      console.log("websocket message:", event.data);
    };

    client.onclose = (reason) => {
      console.log("websocket close:", reason.code);
    };

    client.onerror = (error) => {
      console.log("websocket error:", error.message);
    };
  } catch (error) {
    console.log("connect error:", error.message);
  }
};

connect("ws://ServerHere:PortHere");

【问题讨论】:

    标签: node.js websocket ws


    【解决方案1】:

    您实际上在服务器上收到了一个Buffer 对象。在收到的数据上调用.toString(),它将是可读的文本。 Buffer 是二进制数据。这就是通过socket 发送数据的方式。

    也许你想看看socket.io 包,它使一开始使用套接字更容易。

    【讨论】:

    • 感谢您提供的信息,我非常感谢。而且我认为您不能使用 socket.io 从我在某处读到的内容连接到 websocket?
    • 是的。您必须在 client-serverside 上使用 socket.io
    • 但以上是否回答了您的问题?还是帮你? .
    猜你喜欢
    • 2020-08-06
    • 1970-01-01
    • 2019-09-27
    • 1970-01-01
    • 2012-08-24
    • 2021-05-06
    • 1970-01-01
    • 2018-11-03
    • 2022-01-07
    相关资源
    最近更新 更多