6

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

    });
});
zbeyens
  • 321
  • 1
  • 5
  • 16
  • 2
    This isn't really a duplicate, it's not asking how to convert Buffer to ArrayBuffer, it's asking how to configure ws so it gives you ArrayBuffers in the first place. For the record, you can just do the same thing you do with the browser WebSocket interface - in the example above, you'd add `socket.binaryType = 'arraybuffer';` before the call to `socket.on` – Squatting Bear May 07 '18 at 05:36

1 Answers1

6

Just had to convert the Buffer to an ArrayBuffer

var buf = new Uint8Array(message).buffer;
var dv = new DataView(buf);
Community
  • 1
  • 1
zbeyens
  • 321
  • 1
  • 5
  • 16