node.js:向 TCP 套接字发送和接收字节

node.js: Sending and receiving bytes to a TCP socket

这应该很容易弄清楚,但我感到很沮丧,而且我似乎找不到关于这个相当简单的案例的文档。

我想通过 TCP 连接发送字节(不是字符串)并处理响应。这是我得到的,但它在使用 Buffer 类型时抛出类型异常。当我改用字符串类型时,它发送字节 0xc3 0xbe 0x74 0x01 而不是 0xfe 0x74 0x01(来自 tcpdump)。天知道为什么。

如果我应该改用管道接口,那就太好了,但我似乎无法找到如何对 TCP 流而非文件执行此操作。

const net = require ('net')

const pumpIP = '192.168.1.208'
const pumpPort = 2101
const pumpStr = '\xfe\x74\x01'
const pumpBuffer = Buffer.from(0xfe, 0x74, 0x01)


var pump = new net.Socket()

pump.connect(pumpPort, pumpIP, function() {
    pump.write(pumpBuffer)    // <-- this throws a type error
//  pump.write(pumpStr)       // <-- this sends 0xc3 0xbe 0x74 0x01 instead
})

pump.on('data', function(data) {
//  code to handle data
    pump.destroy()
})

对于您的 Buffer.from(),您需要使用数组。试试这个:

const pumpBuffer = Buffer.from([0xFE, 0x74, 0x01]);

https://nodejs.org/api/buffer.html#buffer_class_method_buffer_from_array