Object.toString() 返回"[blob data]"



我有一个简单的http服务器作为systemd服务在Node中运行,它通过tcp套接字(而不是WS套接字(接收数据。这是代码:

const net = require('net');
const HOST = '0.0.0.0';
const PORT = 6968;
const server = net.createServer();
server.listen(PORT, HOST);
console.log('Server listening on', PORT);
server.on('connection', function(sock) {
console.log('CONNECTED:');
sock.on('data', function (data) {
let message = data.toString().trim();
console.log('message is', message);
console.log('data is', data);
console.log('message type is', typeof(message));
console.log('data is', typeof(data));
});
});

发送到此服务器的数据类型示例如下字符串:

感恩之死^LSugaree^L005:37^L0251-001^LM\r\n

我遇到的具体问题是";let message=data.toString((.trim(("不会返回发送给我的字符串。相反,我会得到如下内容:

"[67B斑点数据]";

服务器接收的对象("数据"(的console.log显示如下内容:

"lt;缓冲器44 72 61 67 69 6e 20等>quot;

(消息(的类型是";字符串";。(数据(的类型是";对象";。

我一整天都在研究这个问题,并尝试了许多不同的方法,但我尝试过的任何东西都不会返回到我想要的字符串,尽管我只需输入终端命令查看端口即可看到字符串:

"socat TCP4侦听:6968,reuseaddr,fork-&";

有人看到我做错了什么吗?

以下是从该网站被盗的一个示例:https://riptutorial.com/node-js/example/22405/a-simple-tcp-server

const net = require("net");
const HOST = "0.0.0.0";
const PORT = 6968;
const server = net.createServer();
server.listen(PORT, HOST);
console.log("Server listening on", PORT);
server.on("connection", function (socket) {
console.log("A new connection has been established.");
// Now that a TCP connection has been established, the server can send data to
// the client by writing to its socket.
socket.write("Hello, client.");
// The server can also receive data from the client by reading from its socket.
socket.on("data", function (chunk) {
console.log(`Data received from client: ${chunk.toString().trim()}.`);
});
// When the client requests to end the TCP connection with the server, the server
// ends the connection.
socket.on("end", function () {
console.log("Closing connection with the client");
});
// Don't forget to catch error, for your own sake.
socket.on("error", function (err) {
console.log(`Error: ${err}`);
});
});

如果将来有人无意中发现了这一点,问题是我是个白痴。简单的解决方案是使用";消息";创建数组:

let dataArray = message.split('f');

(我碰巧知道发送给我的数据使用"\f"作为分隔符。(

然后,我可以根据自己的意愿使用数组来处理数据。

最新更新