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

时间:2013-08-01 09:36:06

标签: javascript html5 performance

我有一个接收二进制消息的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);
}

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

1 个答案:

答案 0 :(得分:22)

您是否考虑过:

socket.binaryType = 'arraybuffer';

该功能变为:

function convert(data) {
     return new Uint8Array(data);
}

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