3

I'm trying to send typed arrays (Uint16Array) from a browser to node.js trough a binary socket but I'm getting incoherent values when I receive them in node. I read lot of documentation but there is something that I don't understand...

Here is the browser-side code :

var ws = new WebSocket('ws://127.0.0.1:8080');
ws.binaryType = "arraybuffer";

var message = new Uint16Array(3);
message[0] = 123;
message[1] = 456;
message[2] = 789;

ws.onopen = function() {
    ws.send(message.buffer);
};

And this is the server code (I'm using https://github.com/einaros/ws) :

    var WebSocketServer = require('ws').Server;
    var wss = new WebSocketServer({port: 8080});
    wss.on('connection', function(ws) {

        ws.on('message', function(buffer, flags) {

            var message = new Uint16Array(buffer);
            console.log(message[0]); // 123
            console.log(message[1]); // 0
            console.log(message[2]); // 200

        });
    });

Would you have any idea where this variation could come from? Thanks to all !

Dimitri

1 Answer 1

2

Hilariously late answer, but it looks like ws flattens typed arrays into byte-sized buffers. 123 comes through fine because it fits into the low byte of the uint16. 0 is the high byte of 123. 200 is just the low byte of 456:

456 & 0xFF // 200

The buffer you receive in your server's message handler should be twice as long as the Uint16Array you sent. You'll have to manually reconstruct the uint16's yourself.

var WebSocketServer = require('ws').Server;
var wss = new WebSocketServer({port: 8080});

// Pre-allocate so we're not incurring allocation overhead on every message
var message = new Uint16Array(3);

wss.on('connection', function(ws) {
    ws.on('message', function(buffer, flags) {
        for (var i = 0; i < uint16Array.length; i++) {
            message[i] = buffer[2*i] | message[2*i+1] << 8;
        }

        console.log(message[0]); // 123
        console.log(message[1]); // 456
        console.log(message[2]); // 789
    });
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.