-
Notifications
You must be signed in to change notification settings - Fork 7
/
index.js
55 lines (38 loc) · 1.2 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
var swarm = require('discovery-swarm')
var gossip = require('secure-gossip')
var EventEmitter = require('events')
var util = require('util')
util.inherits(Pubsub, EventEmitter)
function Pubsub (topic, opts) {
if (!(this instanceof Pubsub)) { return new Pubsub(topic, opts) }
if (!topic) { throw new Error('a topic must be set') }
if (typeof topic !== 'string') { throw new Error('topic must be a string') }
opts = opts || {}
opts.port = opts.port || 0
EventEmitter.call(this)
this.gossip = gossip(opts.gossip)
this.id = this.gossip.keys.public
this.swarm = swarm()
this.swarm.join(topic)
var firstConn = false
var self = this
this.swarm.on('connection', function (connection) {
console.log('found + connected to peer')
var g = self.gossip.createPeerStream()
connection.pipe(g).pipe(connection)
if (!firstConn && this.connections.length === 1) {
firstConn = true
self.emit('connected')
}
})
// TODO: fire event when you have no peers left
// ...
this.swarm.listen(opts.port)
this.gossip.on('message', function (msg) {
self.emit('message', msg)
})
this.publish = function (msg) {
self.gossip.publish(msg)
}
}
module.exports = Pubsub