Browse Source

use bind-easy

session-estimator
Mathias Buus 3 years ago
parent
commit
2279c8b4da
  1. 39
      lib/bind.js
  2. 6
      lib/io.js
  3. 1
      package.json

39
lib/bind.js

@ -1,39 +0,0 @@
// TODO: move to module so we can have udp+tcp mode also on the same port etc etc
const dgram = require('dgram')
module.exports = async function bind (port) {
return new Promise((resolve, reject) => {
const socket = dgram.createSocket('udp4')
let tries = 1
socket.bind(port)
socket.on('listening', onlistening)
socket.on('error', onerror)
function onlistening () {
cleanup()
resolve(socket)
}
function onerror (err) {
if (port === 0 || tries >= 5) {
cleanup()
reject(err)
return
}
if (++tries < 5) {
socket.bind(++port)
} else {
port = 0
socket.bind(0)
}
}
function cleanup () {
socket.removeListener('error', onerror)
socket.removeListener('listening', onlistening)
}
})
}

6
lib/io.js

@ -1,8 +1,8 @@
const FIFO = require('fast-fifo')
const sodium = require('sodium-universal')
const c = require('compact-encoding')
const bind = require('bind-easy')
const peer = require('./peer')
const bind = require('./bind')
const { INVALID_TOKEN, TIMEOUT, DESTROY } = require('./errors')
const VERSION = 0b11
@ -133,13 +133,13 @@ module.exports = class IO {
}
async _bindSockets () {
this.serverSocket = typeof this._bind === 'function' ? this._bind() : await bind(this._bind)
this.serverSocket = typeof this._bind === 'function' ? this._bind() : await bind.udp(this._bind)
try {
// TODO: we should reroll the socket is it's close to our preferred range of ports
// to avoid it being accidentally opened
// We'll prop need additional APIs for that
this.clientSocket = await bind(0)
this.clientSocket = await bind.udp()
} catch (err) {
await new Promise((resolve) => this.serverSocket.close(resolve))
this.serverSocket = null

1
package.json

@ -4,6 +4,7 @@
"description": "Make RPC calls over a Kademlia based DHT",
"main": "index.js",
"dependencies": {
"bind-easy": "^1.0.0",
"compact-encoding": "^2.1.0",
"fast-fifo": "^1.0.0",
"kademlia-routing-table": "^1.0.0",

Loading…
Cancel
Save