NodeJS如何使用原始十六进制发送TCP数据包

tot*_*oti 1 node.js

我是 node 的新手,并试图编写发送原始十六进制数据的最小 tcp 客户端。如果我应该使用缓冲区,那么如何使用?如果我可以将十六进制作为字符串发送,那么如何发送?非常感谢指导!

继承人当前的,不工作的代码:

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');
});
Run Code Online (Sandbox Code Playgroud)

服务器:

nc -lvp 3000
Run Code Online (Sandbox Code Playgroud)

tot*_*oti 5

这解决了它:

var bytesToSend = [0x50, 0x4f, ...],
    hexVal = new Uint8Array(bytesToSend);
Run Code Online (Sandbox Code Playgroud)