gpt4 book ai didi

node.js - 我什么时候应该在 NodeJs net.socket 上使用 socket.pipe()

转载 作者:太空宇宙 更新时间:2023-11-03 23:32:45 24 4
gpt4 key购买 nike

我有 NodeJs 处理来自 GPRS 设备的传入 tcp 连接。

我的问题是,我应该在 net.createServer(...) 范围内使用 socket.pipe(socket) 吗?

是否以允许双工通信的形式调用此pipe(),即gprs->node和node->gprs?或者我可以避免调用这个方法吗?

最佳答案

您没有分享您的代码,但一般来说pipe()对于实现双工通信不是必需的因为 tcp 套接字本质上是双向的。

net.createServer(function (gprsSocket) {
gprsSocket.on('data', function (data) {
// incoming data
// every time the GPRS is writing data - this event is emited
})

// outgoing data
// call this whenever you want to send data to
// the GPRS regardless to incoming data
gprsSocket.write('hello\n')
})

回答你的问题 - 不,没有必要。事实上,调用 socket.pipe(socket) 会将收到的所有数据发送回 GPRS。基本上是在做类似的事情(尽管不完全相同)

gprsSocket.on('data', function (data) {
// echo the data back to the gprs
gprsSocket.write(data);
})

pipe() 用于将一个流重定向到另一个流

// redirect all data to stdout
gprsSocket.pipe(process.stdout)

关于node.js - 我什么时候应该在 NodeJs net.socket 上使用 socket.pipe(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36314892/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com