[英]Decoding buffer received from client in websocket
我在節點 js 中有簡單的 websocket 服務器和客戶端,
我的服務器
var WebSocketServer = require("ws").Server;
var wsServer = new WebSocketServer({ port: 5555 });
wsServer.on("connection", function (ws) {
console.log("Connection established!");
ws.send("Connection established!");
ws.on("message", function (msg) {
ws.send("Got your message!");
console.log(msg);
console.log(msg.data);
});
});
客戶端如下所示
var ws = new WebSocket("ws://localhost:5555");
function sendMsg() {
ws.send(document.getElementById("msg").value);
}
ws.onmessage = function(event) {
console.log(event);
console.log("server mgs:", event.data);
}
ws.onerror = function(event) {
console.log("Server err:", event.data);
}
連接正在建立,但收到的消息顯示如下所示,而不是我從客戶端發送的實際文本。我在 mac 中使用可視代碼終端。
Received: <Buffer 74 65 74>
Received: <Buffer 74 65 74 64 64>
嘗試使用Buffer.toString() 。 然后您的服務器代碼將包括:
ws.on("message", function (msg) {
ws.send("Got your message!");
console.log(msg.toString());
});
請注意,默認格式是utf8 。 檢查它是否符合您的需求。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.