我已经在node.js上编写了一个简单的TCP服务器,用于向Chrome应用程序发送一些数据。在Chrome应用程序中,当我接收到数据时,我使用下面的函数将其转换为字符串,但是出现了异常 "Uint16Array的字节长度应该是2的倍数"
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应用程序的代码:
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));
}