【问题标题】:Receiving <Buffer> from Node JS Websocket从 Node JS Websocket 接收 <Buffer>
【发布时间】:2022-01-15 22:05:09
【问题描述】:

我只是想从 websocket 服务器记录消息,但我似乎只接收缓冲区数据。下面的例子试图连接到https://www.piesocket.com/websocket-tester

我做错了什么?

import WebSocket from 'ws'
const demoStreamer = new WebSocket('wss://demo.piesocket.com/v3/channel_1? 
api_key=oCdCMcMPQpbvNjUIzqtvF1d2X2okWpDQj4AwARJuAgtjhzKxVEjQU6IdCjwm&notify_self')

demoStreamer.on('message', (data) => {
  console.log(data);
});

// OUTPUT: 
// <Buffer 7b 22 69 6e 66 6f 22 3a 22 59 6f 75 20 61 72 65 20 75 73 69 6e 67 20 61 20 74 65 73 
// 74 20 61 70 69 20 6b 65 79 22 7d>
// <Buffer 54 65 73 74 20 6d 65 73 73 61 67 65>
// <Buffer 54 65 73 74 20 6d 65 73 73 61 67 65>

【问题讨论】:

    标签: node.js websocket


    【解决方案1】:

    7b 22 69 6e 66 6f 22 3a 22 59 6f 75 20 61 72 65 20 75 73 69 6e 67 20 61 20 74 65 73 74 20 61 70 69 20 6b 65 79 22 7d{"info":"You are using a test api key"} 的十六进制表示

    只需将缓冲区转换为字符串:

    demoStreamer.on('message', (data) => {
      console.log(data.toString()); // "{\"info\":\"You are using a test api key\"}"
      // Retrieve the info message:
      console.log(JSON.parse(data).info); // "You are using a test api key"
    });
    

    【讨论】:

      猜你喜欢
      • 2012-11-20
      • 2021-02-28
      • 2019-07-17
      • 1970-01-01
      • 2023-01-24
      • 1970-01-01
      • 2021-03-06
      • 2016-02-26
      • 2013-03-31
      相关资源
      最近更新 更多