如何将二进制格式转换为字符串(大端)格式

how to convert binary to string (big endian) format

我有一个 tcp 套接字,我尝试从那里获取二进制数据并通过节点 js 将其转换为字符串

这是我的代码

const Net = require('net');
const port = 4000;
const host = '0.0.0.0';

const client = new Net.Socket();
client.connect({ port: port, host: host }), function() {
    console.log('TCP connection established with the server.');

    client.write('Hello, server.');
};
client.on('data', function(chunk) {
    console.log(chunk);
    
    client.end();
});

client.on('end', function() {
    console.log('Requested an end to the TCP connection');
}); 

输出为

<缓冲区 82 44 53 53 76 57 37 56 4c 6d 62 ed 14 00 00 00 00 00 00 00 00 00 00 00 00 4c 05 e5 58 00 00 00 00 e1 8f 80>

我认为您只是缺少设置编码。我认为您需要做的就是在声明后 client.setEncoding("utf8") ,它应该可以工作。如果没有,那么您应该查看 Buffer api 并尝试将二进制数据转换为不同的格式。

以下是有用的参考资料:

https://nodejs.org/api/net.html#event-data

https://nodejs.org/api/net.html#socketsetencodingencoding

https://nodejs.org/api/buffer.html