js-libp2p-tcp/src/index.js

86 lines
1.8 KiB
JavaScript
Raw Normal View History

2016-05-09 11:14:40 +02:00
'use strict'
2016-08-05 14:22:18 +02:00
const net = require('net')
const toPull = require('stream-to-pull-stream')
2016-03-14 16:57:54 +00:00
const mafmt = require('mafmt')
2018-04-02 18:57:59 +01:00
const withIs = require('class-is')
const includes = require('lodash.includes')
2016-08-05 14:22:18 +02:00
const isFunction = require('lodash.isfunction')
const Connection = require('interface-connection').Connection
const once = require('once')
2016-08-05 14:22:18 +02:00
const debug = require('debug')
const log = debug('libp2p:tcp:dial')
2015-09-15 19:08:19 +01:00
2016-08-05 14:22:18 +02:00
const createListener = require('./listener')
2017-04-07 11:51:56 -04:00
function noop () {}
class TCP {
dial (ma, options, callback) {
2016-08-05 14:22:18 +02:00
if (isFunction(options)) {
2017-04-07 11:51:56 -04:00
callback = options
options = {}
}
2018-02-07 06:26:02 +00:00
callback = once(callback || noop)
2016-08-05 14:22:18 +02:00
const cOpts = ma.toOptions()
log('Connecting to %s %s', cOpts.port, cOpts.host)
const rawSocket = net.connect(cOpts)
2017-04-07 11:51:56 -04:00
rawSocket.once('timeout', () => {
log('timeout')
rawSocket.emit('error', new Error('Timeout'))
})
2017-04-07 11:51:56 -04:00
rawSocket.once('error', callback)
rawSocket.once('connect', () => {
2017-04-07 11:51:56 -04:00
rawSocket.removeListener('error', callback)
callback()
})
const socket = toPull.duplex(rawSocket)
const conn = new Connection(socket)
2017-04-07 11:51:56 -04:00
conn.getObservedAddrs = (callback) => {
return callback(null, [ma])
}
return conn
}
2016-08-05 14:22:18 +02:00
createListener (options, handler) {
if (isFunction(options)) {
handler = options
options = {}
}
2018-02-07 06:40:00 +00:00
handler = handler || noop
2016-08-05 14:22:18 +02:00
return createListener(handler)
}
2016-03-14 16:57:54 +00:00
2016-08-05 14:22:18 +02:00
filter (multiaddrs) {
2016-03-14 16:57:54 +00:00
if (!Array.isArray(multiaddrs)) {
multiaddrs = [multiaddrs]
}
2016-03-14 16:57:54 +00:00
return multiaddrs.filter((ma) => {
if (includes(ma.protoNames(), 'p2p-circuit')) {
return false
}
if (includes(ma.protoNames(), 'ipfs')) {
ma = ma.decapsulate('ipfs')
}
2016-03-14 16:57:54 +00:00
return mafmt.TCP.matches(ma)
})
}
2015-09-15 19:08:19 +01:00
}
2017-04-07 11:51:56 -04:00
2018-04-02 18:57:59 +01:00
module.exports = withIs(TCP, { className: 'TCP', symbolName: '@libp2p/js-libp2p-tcp/tcp' })