Send and receive binary data over web sockets in Javascript?

后端 未结 4 1965
情话喂你
情话喂你 2020-12-04 14:37

It is possible to send and receive binary data over web sockets in Javascript? Could I, for example, implement an SSH client using web sockets?

4条回答
  •  感动是毒
    2020-12-04 15:03

    Now you can send and receive binary data easily, this article explain lot of thinks : http://blog.mgechev.com/2015/02/06/parsing-binary-protocol-data-javascript-typedarrays-blobs/

    Here is how I receive binary numpy array sent with python (my_nparray.tobytes()) in my browser:

    ws = new WebSocket("ws://localhost:51234");
    ws.binaryType = 'blob';
    var buffer;
    
    ws.onmessage = function (evt) {
        var reader = new FileReader();
        reader.readAsArrayBuffer(evt.data);
        reader.addEventListener("loadend", function(e)
        {
            buffer = new Uint16Array(e.target.result);  // arraybuffer object
        });
    };
    

    You can convert typed array to javascript array with this:

    Array.prototype.slice.call(buffer.slice());
    

提交回复
热议问题