mafintosh / discovery-swarm

A network swarm that uses discovery-channel to find peers
MIT License
376 stars 57 forks source link

add .connect option #29

Closed juliangruber closed 7 years ago

juliangruber commented 7 years ago

this lets you connect streams yourself.

I stumbled upon this while implementing a throttling feature for desktop. Currently I would have to do something like

disc({
  stream: info => {
    // this is the normal throttle logic
    const input = throttle(speed)
    const output = throttle(speed)

    input.pipe(stream).pipe(output)
    const throttled = duplex(input, output)
    stream.on('error', err => throttled.emit('error', err))

    // this is all the extra plumbing you have to do
    stream.on('handshake', err => throttled.emit('error', err))

    throttled.destroy = () => stream.destroy()

    Object.defineProperty(throttled, 'id', { get: () => stream.id })
    Object.defineProperty(throttled, 'remoteId', { get: () => stream.remoteId })

    return throttled
  }
})

With this patch, it can be implemented as simple as

disc({
  connect: (local, remote) => {
    pump(local, throttle(speed), remote, throttle(speed), local)
  }
})
mafintosh commented 7 years ago

4.4.0 - this is great!