Search code examples
javascriptserializationwebsocketmsgpack

Deserialize data from websocket response


I'm am trying to deserialize a WebSocket response with the package msgpacket.

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. 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.


Solution

  • I was able to solve the problem.

    I figured out I needed to convert a blob into an array buffer

    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