2.0.0 • Published 5 years ago

pull-flood v2.0.0

Weekly downloads
-
License
MIT
Repository
-
Last release
5 years ago

pull-flood

simplest gossip protocol.

protocol

when creating a new message, send it to all connected peers. when receiving a message, if you have not already seen it, send it to all peers except the one who sent it to you.

example

var Flood = require('pull-flood')

var flood = Flood({
  onMessage: function (msg) {
    console.log('received', msg)
  },
  capacity: 100, //only keep 100 messages in memory
  //too many messages in buffer, dropped this.
  onDrop: function (msg) {
    console.log('dropped:', msg)
  },
  //connected to a peer
  onConnect: function (id) {
    console.log('connected:', id)
  },
  //disconnected from a peer
  onDisconnect: function (id) {
    console.log('disconnected:', id)
  }
})

flood.data //access to raw data

//create a duplex stream to a remote instance. 
var stream = flood.createStream({id: <remote_id>})

duplex stream

This module uses a duplex stream (two way communication) This sort of stream is used in communication protocols to use something with a duplex stream, you connect it both ways:

var net = require('pull-net')
var toPull = require('stream-to-pull-stream')
var PJSON = require('pull-json-doubleline')

//accept duplex streams on the server
net.createServer(function (stream) {
  var id = stream.remoteAddress + ':' + stream.remotePort //or some other way to set an id
  var remote = toPull.duplex(stream)
  pull(
    remote,
    PJSON.parse(),
    flood.createStream({id: id}),
    PJSON.stringify(),
    remote
  )
}).listen(PORT)


//create a duplex stream from a client
var remote = toPull.duplex(net.connect(address, port))
var id = address+':'+port
pull(
  remote,
  PJSON.parse(),
  flood.createStream({id: id}),
  PJSON.stringify(),
  remote
)

api

Flood(opts) => flood

create a pull-flood instance.

flood.append(msg)

append a message to the data. if msg is new, will call opts.onChange and broadcast the change to any peers.

flood.createStream(opts)

returns a duplex stream. to communicate with a remote server, you will need to pass this through an encoding, for example pull-json-doubleline

opts.id is mandatory. it should be set to something unique that identifies the peer, otherwise opts.onConnect calls will not make sense.

flood.data <Array<{key: <receive_timestamp>, value: msg>>

An array of messages in the system. read from this value, but do not write! The key of each message is the local time that message was received. the value is the message itself.

License

MIT

2.0.0

5 years ago

1.0.0

5 years ago