Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Receive an ArrayBuffer on WebSocket (ws) [duplicate]

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

    });
});
like image 311
zbeyens Avatar asked Aug 26 '16 20:08

zbeyens


1 Answers

Just had to convert the Buffer to an ArrayBuffer

var buf = new Uint8Array(message).buffer;
var dv = new DataView(buf);
like image 134
zbeyens Avatar answered Nov 05 '22 08:11

zbeyens