forked from RangerMauve/hyperswarm-proxy-ws
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.js
58 lines (43 loc) · 1.47 KB
/
client.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
56
57
58
const DSwamProxyClient = require('@dswarm/proxy/client')
const websocket = require('websocket-stream')
const DEFAULT_PORT = '4977' // HYPR on a cellphone keypad
const LOCAL_PROXY = `ws://localhost:${DEFAULT_PORT}`
const DEFAULT_PROXY = [LOCAL_PROXY]
const DEFAULT_RECONNECT_DELAY = 1000
class DSwarmProxyWSClient extends DSwamProxyClient {
constructor (opts = {}) {
super(opts)
const { proxy = DEFAULT_PROXY, reconnectDelay = DEFAULT_RECONNECT_DELAY } = opts
this.reconnectDelay = reconnectDelay
this.proxy = null
this._urls = typeof proxy === 'string' ? [proxy] : proxy
this._urlIndex = 0
this.reconnect()
}
reconnect () {
this._nextUrl();
const localSocket = websocket(LOCAL_PROXY)
// Re-emit errors
localSocket.on('error', (e) => this.emit('connection-error', e))
localSocket.once('error', () => {
// Couldn't connect to a local proxy
// Attempt to connect to the internet proxy
const proxySocket = websocket(this.proxy)
// Re-emit errors
proxySocket.on('error', (e) => this.emit('connection-error', e))
proxySocket.once('close', () => {
setTimeout(() => {
if (this.destroyed) return
this.reconnect()
}, this.reconnectDelay)
})
super.reconnect(proxySocket)
})
super.reconnect(localSocket)
}
_nextUrl() {
this.proxy = this._urls[this._urlIndex++ % this._urls.length]
return this.proxy
}
}
module.exports = DSwarmProxyWSClient