duplex-to-multiplex
v1.0.0
Published
Multiplex an existing duplex stream
Downloads
5
Readme
duplex-to-multiplex
Multiplex an existing duplex stream
Install
$ npm install duplex-to-multiplex
Usage
'use strict'
var net = require('net')
var duplexToMultiplex = require('duplex-to-multiplex')
var server = net.createServer(function (socket) {
socket.on('close', function () {
server.close()
server.unref()
})
duplexToMultiplex(socket, function (plex) {
// create multiple sub-streams
var heartbeat = plex.createStream('heartbeat')
heartbeat.on('data', function (data) {
console.log('Received:', data.toString())
heartbeat.end()
})
heartbeat.on('end', function () {
console.log('heartbeat stream on server has ended')
})
heartbeat.write(new Buffer('PING'))
}, {
end: function (err) {
console.log('underlying duplex stream source (socket) has ended on server')
}
})
})
server.listen(8888, function () {
var client = net.connect(8888)
duplexToMultiplex(client, function (plex) {
// receive multiple sub-streams
var heartbeat = plex.receiveStream('heartbeat')
heartbeat.on('data', function (data) {
console.log('Received:', data.toString())
heartbeat.write(new Buffer('PONG'))
})
heartbeat.on('end', function () {
console.log('heartbeat stream on client has ended')
client.end()
})
}, {
end: function (err) {
console.log('underlying duplex stream source (socket) has ended on client')
}
})
})
API
duplexToMultiplex(stream, callback, options)
{
stream: DuplexStream,
callback: Function,
options: Object
}
The given callback returns a stream capable of adding additional streams. See example for more details.
You can also specify an end
function on the options
object to notify you if either underlying duplex stream has ended.
{
end: function (err) {
// handle stream cleanup
}
}
TODO
- More Tests
License
MIT