How get real raw data over tcp nodejs

33 views Asked by At

I want to retrieve data via TCP, but the data obtained becomes the presence of new lines.
However, if you use other tools such as putty, the results look good. Where do you think the problem?. Thank you.

I try with code:

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());
});

And my code result: enter image description here


But if use other tools like putty and hypeterminal, result look good data:
&&
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
!!
1

There are 1 answers

0
Ricardo Gellman On

You could try accumulate the data in buffer and print it formatted by:

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');
});