How get real raw data over tcp

41 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 lies. Thankyou


const net = require('node:net');
net.isIP('127.0.0.1'); // returns 4
const client = net.createConnection({ port: 1024 }, () => {
  // 'connect' listener.
  console.log('connected to server!');
  client.write('world!\r\n');
});

// Set encoding for the socket
utf8=client.setEncoding('utf8');

// Handle incoming data
utf8.on('data', (data) => {
  console.log('Received data utf8:', data);
  var rawBuffer = Buffer.from(data);
  console.log('Buffer Data as String:', rawBuffer.toString('utf-8'));

Result from my code:
&&

0101
RDG-061
010
20

0103
1
0
1048
233
0105240

Result from raw Putty (real data):
0101RDG-061
01020
01031
01044829
010524030

1

There are 1 best solutions below

1
ishaan On

I believe that's because different OS has different conventions for line endings and hence you might be getting this output. you can use linebuffer and customise it according to your need.

let lineBuffer = '';

client.setEncoding('utf8');

client.on('data', (data) => {
  lineBuffer += data;
  while (lineBuffer.includes('\r\n')) {
    const [line, rest] = lineBuffer.split('\r\n', 2);
    console.log('Received data:', line);
    lineBuffer = rest;
  }
});