从WebSocket接收的JavaScript blob中读取字节

Roe*_*den 10 javascript performance html5

我有一个WebSocket接收二进制消息,我想迭代字节.

我提出了以下转换功能......

// Convert the buffer to a byte array.
function convert(data, cb) {
    // Initialize a new instance of the FileReader class.
    var fileReader = new FileReader();
    // Called when the read operation is successfully completed.
    fileReader.onload = function () {
        // Invoke the callback.
        cb(new Uint8Array(this.result));
    };
    // Starts reading the contents of the specified blob.
    fileReader.readAsArrayBuffer(data);
}
Run Code Online (Sandbox Code Playgroud)

这确实有效,但性能很糟糕.有没有更好的方法来允许读取字节?

Esa*_*ija 22

你有没有考虑过:

socket.binaryType = 'arraybuffer';
Run Code Online (Sandbox Code Playgroud)

该功能变为:

function convert(data) {
     return new Uint8Array(data);
}
Run Code Online (Sandbox Code Playgroud)

这实际上不需要做任何工作,因为它只是缓冲区的一个视图.