我什么时候应该在NodeJ的net.socket上使用socket.pipe()



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

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

是否以允许双工通信的形式调用此管道(),即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('hellon')
})

回答你的问题——不,没有必要。事实上,呼叫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)

最新更新