multiple listeners, more tests, understand multiaddr on the listen function

This commit is contained in:
David Dias
2016-03-04 18:58:01 +00:00
parent 506b4cbcfe
commit 0b6361e27a
5 changed files with 134 additions and 14 deletions

View File

@ -1,10 +1,61 @@
var tcp = require('net')
const debug = require('debug')
const log = debug('libp2p:tcp')
const tcp = require('net')
exports = module.exports
exports = module.exports = TCP
exports.dial = function (multiaddr, options) {
options.ready = options.ready || function noop () {}
return tcp.connect(multiaddr.toOptions(), options.ready)
function TCP () {
if (!(this instanceof TCP)) {
return new TCP()
}
const listeners = []
this.dial = function (multiaddr, options) {
if (!options) {
options = {}
}
options.ready = options.ready || function noop () {}
return tcp.connect(multiaddr.toOptions(), options.ready)
}
this.createListener = (multiaddrs, options, handler, callback) => {
if (typeof options === 'function') {
callback = handler
handler = options
options = {}
}
if (!Array.isArray(multiaddrs)) {
multiaddrs = [multiaddrs]
}
var count = 0
multiaddrs.forEach((m) => {
const listener = tcp.createServer(handler)
listener.listen(m.toOptions(), () => {
log('listening on: ', m.toString())
if (++count === multiaddrs.length) {
callback()
}
})
listeners.push(listener)
})
}
this.close = (callback) => {
if (listeners.length === 0) {
throw new Error('there are no listeners')
}
var count = 0
listeners.forEach((listener) => {
listener.close(() => {
if (++count === listeners.length) {
callback()
}
})
})
}
}
exports.createListener = tcp.createServer