2013-08-01 9 views
9

私はバイナリメッセージを受け取るWebSocketを持っています。WebSocketによって受信されたJavaScriptのBLOBからバイトを読み取る

私は、次の変換機能を思い付いた...

// 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); 
} 

これは、作業を行いますが、パフォーマンスはひどいです。読み込みバイトを許可する良い方法はありますか?

+0

使用しているブラウザは何ですか? – karthick

+0

Google Chromeは私が使用しているブラウザです。 –

+0

どのタイプが 'データ 'ですか – Esailija

答えて

20

あなたは考えがあります:

socket.binaryType = 'arraybuffer'; 

機能は次のようになります。それは、バッファにだけ表示ですので、実際にすべての作業を行う必要はありません

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

+1

メンテナンス性とパフォーマンスの面で大幅な改善。すばらしいです! –

+0

ありがとう、これは素晴らしい! – velotron