protomux
Multiplex multiple message oriented protocols over a stream
npm install protomux
Usage
const Protomux = require('protomux')
const c = require('compact-encoding')
const mux = new Protomux(aStreamThatFrames)
const cool = mux.addProtocol({
name: 'cool-protocol',
version: {
major: 1,
minor: 0
},
messages: [
c.string,
c.bool
],
onremoteopen () {
console.log('the other side opened this protocol!')
},
onemoteclose () {
console.log('the other side closed this protocol!')
},
onmessage (type, message) {
console.log('the other side sent a message', type, message)
}
})
cool.send(0, 'a string')
cool.send(1, true)
API
mux = new Protomux(stream, [options])
Make a new instance. stream
should be a framed stream, preserving the messages written.
Options include:
{
alloc (size) {},
async onacceptprotocol ({ name, version }) {}
backlog: 128
}
const p = mux.addProtocol(opts)
Add a new protocol.
Options include:
{
name: 'name of the protocol',
version: {
major: 0,
minor: 0
},
messages: [
...
],
async onremoteopen () {},
async onremoteclose () {},
async onmessage (type, message) {}
}
Each of the functions can also be set directly on the instance with the same name.
p.close()
Closes the protocol
p.send(type, message)
Send a message, type is the offset into the messages array.
p.cork()
Corking the protocol, makes it buffer messages and send them all in a batch when it uncorks.
p.uncork()
Uncork and send the batch.
mux.cork()
Same as p.cork
but on the muxer instance.
mux.uncork()
Same as p.uncork
but on the muxer instance.
License
MIT