反序列化来自 websocket 响应的数据
Deserialize data from websocket response
我正在尝试使用包 msgpacket.
反序列化 WebSocket 响应
尝试反序列化数据包响应时出现错误:
Uncaught Error: Invalid argument: The byte array to deserialize is empty.
这里是一个基本的片段展示了这一点。我正在使用 echo.websocket.org 来测试这个。它发回它收到的相同响应。
this.socket = new WebSocket('wss://echo.websocket.org');
this.socket.onopen = () => {
console.log('connected');
var sourceData = {
hello: 1,
world: "test"
};
var data = msgpack.serialize(sourceData);
this.socket.send(data.buffer);
var after = msgpack.deserialize(data.buffer);
console.log(after);
}
this.socket.onmessage = function (event) {
var data = msgpack.deserialize(new Uint8Array(event.data));
console.log(data);
};
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<script src="https://raw.githack.com/ygoe/msgpack.js/master/msgpack.min.js"></script>
</body>
</html>
我只是在收到 WebSocket 响应后尝试检索数据。
我能够解决问题。
我发现我需要将 blob 转换为数组缓冲区
这就是有效的方法
var blob = event.data;
var arrayBuffer = null;
arrayBuffer = await new Response(blob).arrayBuffer();
var data = msgpack.deserialize(arrayBuffer);
console.log(data);
在此处找到:
我正在尝试使用包 msgpacket.
反序列化 WebSocket 响应尝试反序列化数据包响应时出现错误:
Uncaught Error: Invalid argument: The byte array to deserialize is empty.
这里是一个基本的片段展示了这一点。我正在使用 echo.websocket.org 来测试这个。它发回它收到的相同响应。
this.socket = new WebSocket('wss://echo.websocket.org');
this.socket.onopen = () => {
console.log('connected');
var sourceData = {
hello: 1,
world: "test"
};
var data = msgpack.serialize(sourceData);
this.socket.send(data.buffer);
var after = msgpack.deserialize(data.buffer);
console.log(after);
}
this.socket.onmessage = function (event) {
var data = msgpack.deserialize(new Uint8Array(event.data));
console.log(data);
};
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<script src="https://raw.githack.com/ygoe/msgpack.js/master/msgpack.min.js"></script>
</body>
</html>
我只是在收到 WebSocket 响应后尝试检索数据。
我能够解决问题。
我发现我需要将 blob 转换为数组缓冲区
这就是有效的方法
var blob = event.data;
var arrayBuffer = null;
arrayBuffer = await new Response(blob).arrayBuffer();
var data = msgpack.deserialize(arrayBuffer);
console.log(data);
在此处找到: