【问题标题】:I get a <Buffer.../> when I console.log message sent by user using Websocket当用户使用 Websocket 发送 console.log 消息时,我得到一个 <Buffer.../>
【发布时间】:2022-01-02 07:31:54
【问题描述】:

index.html:

<script>

    let ws = new WebSocket('ws://localhost:8000');
    ws.onopen = (event) => {
        ws.send('Hola from client Side');
    }
    ws.onmessage = (event) => {
        console.log(event);
    }

</script>

server.js:

const http = require('http');
const websocket = require('ws');

const server = http.createServer((req, res) => {
    res.end("hello")
});

const wss = new websocket.Server({ server });

wss.on('connection', (ws, req) => {
    ws.send('Hello from the websocket server');
    ws.on('message', (msg)=>{ 
        console.log(msg)//---->>> THIS IS LOGING A BUFFER OBJECT, when I am expecting to log 'Hola from client Side'
    })
});

server.listen(8000);

服务器中的console.log正在返回:

<Buffer 48 65 6c 6c 6f 20 66 72 6f 6d 20 63 6c 69 65 6e 74 20 53 69 64 65>

但是我从客户端发送的是

ws.send('Hola from client Side');

感谢任何帮助。

【问题讨论】:

    标签: node.js websocket


    【解决方案1】:

    您需要使用.toString() 函数将缓冲区转换为字符串。

    像这样:

    console.log(msg.toString())
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-04-28
      • 2020-05-06
      • 2021-04-18
      • 2020-11-07
      • 2020-07-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多