G
G
Galdar Turin2020-06-24 22:00:45
Node.js
Galdar Turin, 2020-06-24 22:00:45

How to accept raw data?

To be honest, I don't even know what to call this question. Data comes from the device, but when I receive it and output it to the log file via NGINX and NET SOCKET, I see it differently.

NGINX outputs as - "\x01\x17\x80\x01\x96\x02\x18\x03864006049200006\x042\x00By" 400 157 "-" "-"
NET SOCKET like this - <\Buffer 01 17 80 01 96 02 18 03 38 36 34 33 37 36 30 34 39 32 30 34 31 36 36 04 32 00 42 79 \>

I want to receive data in NET SOCKET like in NGINX, simply because it's easier to break it into the right parts. When outputting the Buffer, everything is turned into a string and this is not at all convenient. The answer is 864006049200006By , and if it is also mixed or comes in a different order, how to understand what's what.

The data itself is sent using the tcp protocol. Here is my crooked piece of code:

Piece of shit
const PORT = 6020;
var  crc16  =  require ('js-crc').crc16;

var net = require('net');
var server = net.createServer();

var clients = [];

net.createServer( (socket) => {

socket.name = socket.remoteAddress + ":" + socket.remotePort;

clients.push(socket);

socket.on('data', (data) => {

    console.log(data)
    console.log(data.toString("utf8"))
    
    //broadcast(socket.name + " message: " + data, socket);
    console.log( crc16(data) )
    socket.write( crc16(data) );
    
});

socket.on('end', () => {
    
    console.log('end')
    clients.splice(clients.indexOf(socket), 1);

});

}).listen(PORT);

console.log(`TCP Server running at localhost port ${PORT}\n`);


Give advice or an example how to me to receive adequate headings and break them. To be able to build an adequate structure of the received data.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Robur, 2020-06-25
@Robur

you can use Buffer.toString() with the desired encoding to get the string.
for example Buffer.toString('hex') will give you '0117800196...', every two digits is one byte.
Or try other encodings if you don't like it.
but in general it is better to work with data in its original form - with numbers. instead of '\x01' you take the first byte and get 1. instead of "\x0386400604920000" you take the bytes in order and get 3 86 40 06 04 and so on.
This is much more convenient than trying to parse a string that was randomly generated from this data.
If you want right here 1v1 as in nginx, then find how it is formatted there and write the same. The question of why, of course, remains.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question