如何将数组缓冲区转换为字符串

2023-12-03

我在 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));
}

现代(Chrome 38+)的方法是,假设编码是 UTF-8:

var decoder = new TextDecoder("utf-8");

function arrayBufferToString(buffer) {
    return decoder.decode(new Uint8Array(buffer));
}

这使用了TextDecoder应用程序接口;看文档以获得更多选项,例如不同的编码。

也可以看看:使用 Encoding API 更轻松地进行 ArrayBufferString 转换 @谷歌开发者

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何将数组缓冲区转换为字符串 的相关文章

随机推荐