multiplex implementation wrapper that is compatible with libp2p Stream Muxer expected interface
Let's define server.js
, which runs two services over a single TCP socket
running port 9000:
var multiplex = require('libp2p-multiplex')
var net = require('net')
var server = net.createServer(function (conn) {
var multi = multiplex(conn, false)
multi.newStream(echoService)
multi.newStream(lengthService)
}).listen(9000)
// Repeat back messages verbatim.
function echoService (err, conn) {
if (err) throw err
conn.on('data', function (data) {
conn.write(data)
})
}
// Respond with the length of each message.
function lengthService (err, conn) {
if (err) throw err
conn.on('data', function (data) {
conn.write(data.length+'\n')
})
}
Let's also define client.js
, multiplexed over a TCP socket that writes to both
services:
var multiplex = require('libp2p-multiplex')
var net = require('net')
var client = net.connect(9000, 'localhost', function () {
var multi = multiplex(client, true)
multi.on('stream', function (conn) {
console.log('got a new stream')
conn.on('data', function (data) {
console.log('message', data.toString())
})
})
})
Run both and see the output on the client:
got a new stream
got a new stream
message hello there!
message 12
var multiplex = require('libp2p-multiplex')
Returns a new multiplexert that multiplexes over the duplex stream transport
.
isListener
should be true when this multiplexer will be used to listen for
streams.
Creates a new stream over the original transport
. The resultant stream is
provided asynchronously via the callback.
Emits an event when a new stream is received by the other side of the transport.
Closes the stream (from either side).
Emitted when the stream has been closed.
Emitted when the stream produces an error.
> npm i libp2p-multiplex