2013-08-01 14 views
9

Possiedo un WebSocket che riceve messaggi binari e desidero iterare sui byte.Lettura di byte da un blob JavaScript ricevuto da WebSocket

Sono venuto con la seguente funzione di conversione ...

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

Questo funziona, ma la prestazione è terribile. C'è un modo migliore per consentire la lettura dei byte?

+0

Qual è il browser che si sta utilizzando? – karthick

+0

Google Chrome è il browser che sto utilizzando. –

+0

che tipo è 'data' – Esailija

risposta

20

Avete considerato:

socket.binaryType = 'arraybuffer'; 

La funzione diventa:

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

Il che non sarà effettivamente hanno a che fare qualsiasi lavoro, perché è solo una vista sul buffer.

+1

Un notevole miglioramento in termini di manutenibilità e prestazioni. Grande! –

+0

Grazie, ha funzionato alla grande! – velotron