我正在测试websocket连接。我希望从客户端向服务器发送JSON对象:
const WebSocket = require('ws');
const wss = new WebSocket.Server({port: 8082});
wss.on("connection", (ws) => {
console.log('server is connected');
ws.on("message", (mesg) => {
const a = mesg.toString();
console.log(a);
});
ws.on("close", () => {
console.log("Client has disconnected!");
});
});
在服务器端:
console.log(mesg)
返回 <Buffer>
console.log(a)
返回 object Object]
JSON.parse(a)
抛出错误信息。
我很困惑。我做错了什么?谢谢!