我想通过TCP检索数据,但是获取到的数据变成了换行符的存在。
但是,如果您使用其他工具(例如 putty),结果看起来不错。您认为问题出在哪里?谢谢。
我尝试使用代码:
const net = require('net');
// Define the host and port of the TCP server
const HOST = '127.0.0.1'; // localhost
const PORT = 1024; // Example port, replace with your server's port
// Create a new TCP client
const client = new net.Socket();
// Connect to the server
client.connect(PORT, HOST, () => {
console.log('Connected to server');
});
ascii = client.setEncoding('ascii');
ascii.on('data', (data) => {
console.log(data);
// var rawBuffer = Buffer.from(data,'ascii');
// console.log('Buffer Data as String:', rawBuffer.toString());
});
我的代码结果:
&&
0101 RDG-061
010 20
0103 1 0 1048 233
0105240 305
010 6144 201
010738
010
810.000000
010910.0 0000 0 0 1101
0.00 0000
01
1110.000 000
011
218.719999
0113.000000
011449.8300 32
0116.000000
011 7-49.830 032
011
811.491255
0119.000000
012 045
0121100
59.4 5312 5
0122.000000
0123 20
0124 50
0125 60
0126
27.6 9694 7 0
127.1824 89
0128 0 01301
777.9549 56
0131 1347 .305 420 013 2134
7.30 5420
01 3334 .999992
013
434.999992
0135
87.8 44383
013683.673508
01 3720 9266
01 3823
01 3910 .000 000
014238.000000
0143.182489
!!
但如果使用 putty 和 hypeterminal 等其他工具,结果看起来不错:
&&
0101RDG-061
01020
01031
01049046
0105240304
0106140440
010737
010810.000000
010910.000000
011010.000000
011110.000000
0113.000000
0116.000000
0117.000000
0118.000000
0119.000000
012320
012450
012560
012620.169584
0127.000036
01301777.954956
01311347.305420
01321347.305420
013334.999992
013434.999992
013717211
013910.000000
014237.000000
0143.000036
!!
您可以尝试累积缓冲区中的数据并按以下格式打印:
const net = require('net');
const HOST = '127.0.0.1';
const PORT = 1024;
const client = new net.Socket();
client.connect(PORT, HOST, () => {
console.log('Connected to server');
});
client.setEncoding('ascii');
let buffer = '';
client.on('data', (data) => {
buffer += data;
const lines = buffer.split('\n');
for (let i = 0; i < lines.length - 1; i++) {
console.log(lines[i]);
}
buffer = lines[lines.length - 1];
});
client.on('close', () => {
console.log('Connection closed');
});