Receive an ArrayBuffer on WebSocket (ws)

zbeyens picture zbeyens · Aug 26, 2016 · Viewed 11.2k times · Source

I would like to handle ArrayBuffer messages received from the client using ws. Client-side, I directly receive an ArrayBuffer thanks to ws.binaryType, but server-side, I don't receive an ArrayBuffer but something like this (string ?) : '< Buffer 00 00 2a 00 00 00 00 00 00 00 00 00 00 00 00 00>'.

How the server can receive an ArrayBuffer ?

Client-side :

var ws = new WebSocket("ws://localhost:3000/");
ws.binaryType = 'arraybuffer';
ws.onopen = function() {
    var buffer = new ArrayBuffer(15);
    var dv = new DataView(buffer);
    dv.setInt16(1, 42);
    ws.send(buffer);
};

Server-side :

var express = require('express'),
app = express(),
server = require('http').createServer(),
WebSocketServer = require('ws').Server,
wss = new WebSocketServer({
    server: server
});

...

wss.on('connection', function(socket) {
    console.log(message);
    //log : <Buffer 00 00 2a 00 00 00 00 00 00 00 00 00 00 00 00 00>


    socket.on('message', function(message) {

        //would like to read and handle the arraybuffer properly

    });
});

Answer

zbeyens picture zbeyens · Aug 27, 2016

Just had to convert the Buffer to an ArrayBuffer

var buf = new Uint8Array(message).buffer;
var dv = new DataView(buf);