[英]Deserialize data from websocket response
I'm am trying to deserialize a WebSocket response with the package msgpacket .我正在尝试使用 package msgpacket反序列化 WebSocket 响应。
When trying to deserialize the packet response I am getting the error:尝试反序列化数据包响应时出现错误:
Uncaught Error: Invalid argument: The byte array to deserialize is empty.
未捕获的错误:无效参数:要反序列化的字节数组为空。
Here is a basic snippet showing this.这是一个显示这一点的基本片段。 I am using echo.websocket.org to test this.
我正在使用 echo.websocket.org 对此进行测试。 It sends back the same response it gets.
它发回它得到的相同响应。
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>
I am simply trying to retrieve the data after receiving the WebSocket response.我只是在收到 WebSocket 响应后尝试检索数据。
I was able to solve the problem.我能够解决这个问题。
I figured out I needed to convert a blob into an array buffer我发现我需要将 blob 转换为数组缓冲区
This is what worked这是有效的
var blob = event.data;
var arrayBuffer = null;
arrayBuffer = await new Response(blob).arrayBuffer();
var data = msgpack.deserialize(arrayBuffer);
console.log(data);
Found here: https://stackoverflow.com/a/55204517/10997917在这里找到: https://stackoverflow.com/a/55204517/10997917
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.