Skip to content Skip to sidebar Skip to footer

How Send Arraybuffer As Binary Via Websocket?

I am working on a project with Mozilla Europe. In this project, I use websocket by Worlize (server-side) and Mozilla (client side), Node.js to try to upload files from a client to

Solution 1:

Gecko11.0 ArrayBuffer send and receive support for binarydata has been implemented.

connection = new WebSocket( 'ws://localhost:1740' );connection.binaryType = "arraybuffer";connection.onopen = onopen;connection.onmessage = onmessage;connection.onclose = onclose;connection.onerror = onerror;

sending Binary data:

functionsendphoto() {
    imagedata = context.getImageData( 0, 0, imagewidth, imageheight );
    var canvaspixelarray = imagedata.data;
    var canvaspixellen = canvaspixelarray.length;
    var bytearray = newUint8Array( canvaspixellen );
    for ( var i = 0; i < canvaspixellen; ++i ) {
        bytearray[i] = canvaspixelarray[i];
    }
    connection.send( bytearray.buffer );
    context.fillStyle = '#ffffff';
    context.fillRect( 0, 0, imagewidth, imageheight );
}

Recieving Binary Data:

if ( event.datainstanceofArrayBuffer ) {
    var bytearray = newUint8Array( event.data );
    var tempcanvas = document.createElement( 'canvas' );
    tempcanvas.height = imageheight;
    tempcanvas.width = imagewidth;
    var tempcontext = tempcanvas.getContext( '2d' );
    var imgdata = tempcontext.getImageData( 0, 0, imagewidth, imageheight );
    var imgdatalen = imgdata.data.length;
    for ( var i = 8; i < imgdatalen; i++ ) {
        imgdata.data[i] = bytearray[i];
    }
    tempcontext.putImageData( imgdata, 0, 0 );
    var img = document.createElement( 'img' );
    img.height = imageheight;
    img.width = imagewidth;
    img.src = tempcanvas.toDataURL();
    chatdiv.appendChild( img );
    chatdiv.innerHTML = chatdiv.innerHTML + "<br />";
}

Solution 2:

Note: Prior to version 11, Firefox only supported sending data as a string.

Source: https://developer.mozilla.org/en/WebSockets/Writing_WebSocket_client_applications

Post a Comment for "How Send Arraybuffer As Binary Via Websocket?"