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

时间:2016-03-30 16:44:05

标签: node.js

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

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

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

1 个答案:

答案 0 :(得分:2)

您没有分享您的代码,但一般来说 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)