我已經在node.js上編寫了一個簡單的TCP服務器來將一些數據發送到Chrome應用程序。在Chrome應用程序,當我得到的數據,我將其轉換成使用下面的函數字符串,我得到一個異常「Uint16Array的字節長度應爲2多」如何將arraybuffer轉換爲字符串
String.fromCharCode.apply(null, new Uint16Array(buffer))
我找不到任何有關可能導致此問題的信息以及如何解決此問題。任何指針都非常感謝。
下面是將數據發送到客戶端的node.js服務器代碼:
socket.on('data', function(data) {
console.log('DATA ' + socket.remoteAddress + ': ' + data);
// Write the data back to the socket,
// the client will receive it as data from the server
var r= socket.write('from server\r\n');
});
下面是鍍鉻的應用程序的代碼:
chrome.sockets.tcp.onReceive.addListener(function (info) {
console.log('onListener registered');
if (info.socketId != socketid)
return;
else {
try {
data = ab2str(info.data);
console.log(data);
}
catch (e) {
console.log(e);
}
}
// info.data is an arrayBuffer.
});
function ab2str(buf) {
return String.fromCharCode.apply(null, new Uint16Array(buf));
}
可以顯示更多的你是如何得到緩衝? – Victory 2014-11-05 10:30:04
一般來說,[這個問題](https://stackoverflow.com/questions/6965107/converting-between-strings-and-arraybuffers)是規範的。不過,我不會去dupehammer。 – Xan 2016-07-11 12:28:27