简体   繁体   中英

NodeJS how to send a TCP packet with raw Hex

I'm new to node, and trying to write the most minimal tcp client that sends raw hexadecimal data. if I should use a buffer then how? if I can send hex as string then how? would really appreciate guidance!

heres the current, not working code:

var hexVal = `504f5354202f6c696e653320485454502f312e310d0a557365722d4167656e743a206e6f64652d6170700d0a4163636570743a202a2f2a0d0a686f73743a203139322e3136382e31342e39343a333030300d0a636f6e74656e742d747970653a206170706c69636174696f6e2f6a736f6e0d0a636f6e74656e742d6c656e6774683a2031390d0a436f6e6e656374696f6e3a20636c6f73650d0a0d0a227b757365726e616d653a202776616c277d22` // my raw hex, unwantendly sent as string


var net = require('net');

var HOST = '192.168.14.94';
var PORT = 3000;

var client = new net.Socket();
client.connect(PORT, HOST, function() {
    console.log('CONNECTED TO: ' + HOST + ':' + PORT);
    client.write(hexVal);
});

client.on('data', function(data) { // 'data' is an event handler for the client socket, what the server sent
    console.log('DATA: ' + data);
    client.destroy(); // Close the client socket completely

});

// Add a 'close' event handler for the client socket
client.on('close', function() {
    console.log('Connection closed');
});

server:

nc -lvp 3000

This solved it:

var bytesToSend = [0x50, 0x4f, ...],
    hexVal = new Uint8Array(bytesToSend);

There is a more convenient way to do what you want, given a hex string send it as raw bytes.

Currently you're using a Uint8Array for which each byte needs to be encoded as 0x41 or something.

However, given a hex string, you can prepare a raw hex buffer as such:

const hexString = "41424344";
const rawHex = Buffer.from(hexString, 'hex');

And then you can write the buffer to the socket:

let client = new net.Socket();
client.connect(PORT, IP, () => {
    console.log("Connected");
    client.write(rawHex); //This will send the byte buffer over TCP
})

Hope this helps

you need to set server first !!!

then and only then client can connect to it ...

var net = require('net');
var config = {
    host: 'localhost',
    port: 3000
};

// var hexVal = `POST /line3 HTTP/1.1
// User-Agent: node-app
// Accept: */*
// host: 192.168.14.94:3000
// content-type: application/json
// content-length: 19
// Connection: close

// "{username: 'val'}"`

var hexVal = `504f5354202f6c696e653320485454502f312e310d0a557365722d4167656e743a206e6f64652d6170700d0a4163636570743a202a2f2a0d0a686f73743a203139322e3136382e31342e39343a333030300d0a636f6e74656e742d747970653a206170706c69636174696f6e2f6a736f6e0d0a636f6e74656e742d6c656e6774683a2031390d0a436f6e6e656374696f6e3a20636c6f73650d0a0d0a
227b757365726e616d653a202776616c277d22` // my raw hex, unwantendly sent as string

var move = {
    forward: hexVal,
    backward: 'READER_BWD'
};

///////////////////////////////////////////////////////////////////////////////////

/* server code */

let server = net.createServer((client) => {
  console.log('client connected');

  client.on('data', data => {
    console.log(data.toString());
    client.write('ACK')
  })

  client.on('end', () => console.log('ended session'))
})
server.listen(3000)

//////////////////////////////////////////////////////////////////////////////

/* client code */

var client = new net.Socket();

client.connect(3000, 'localhost', function () {
        console.log('connected to ' + config.host + ':' + config.port);
        client.write(move.forward, function () {
            console.log('move forward command sent');
        });
});

client.on('data', function (data) {
    var str = data.toString();
    if (str === 'ACK') {
        console.log('ACK received');
        client.write(move.backward, function () {
            console.log('move backward sent');
            client.end();
        });
    }
});

client.on('end', () => {
  console.log('disconnected from server');
});

client.on('error', function (err) {
    console.log('Error : ', err);
});

client.on('close', function () {
    console.log('socket closed');
});


you can even split code of server and client in two separate files too...

then first start server and then start client

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM