当我控制台时,我收到一条<Buffer.../>.log消息,该消息由用户使用 Websocket 发送



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');

感谢您的帮助。

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

像这样:

console.log(msg.toString())

最新更新