How send arraybuffer as binary via Websocket?

寵の児 提交于 2019-11-30 00:11:49
Konga Raju

Gecko11.0 ArrayBuffer send and receive support for binary data 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:

function sendphoto() {
    imagedata = context.getImageData( 0, 0, imagewidth, imageheight );
    var canvaspixelarray = imagedata.data;
    var canvaspixellen = canvaspixelarray.length;
    var bytearray = new Uint8Array( 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.data instanceof ArrayBuffer ) {
    var bytearray = new Uint8Array( 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 />";
}
Dennis
Note: Prior to version 11, Firefox only supported sending data as a string.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!