Skip to content

libp2p/js-libp2p

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

46 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

js-libp2p-multiplex

Build Status Dependency Status js-standard-style

multiplex implementation wrapper that is compatible with libp2p Stream Muxer expected interface

Usage

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

API

var multiplex = require('libp2p-multiplex')

var multi = multiplex(transport, isListener)

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.

multiplex.newStream(function (err, stream) {})

Creates a new stream over the original transport. The resultant stream is provided asynchronously via the callback.

multiplex.on('stream', function (stream) {})

Emits an event when a new stream is received by the other side of the transport.

multiplex.close()

Closes the stream (from either side).

multiplex.on('close')

Emitted when the stream has been closed.

multiplex.on('error')

Emitted when the stream produces an error.

Install

> npm i libp2p-multiplex