-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathConnector.js
55 lines (49 loc) · 1.57 KB
/
Connector.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
var net = require('net')
function Connector(options) {
this.masterIP = options.ip
this.masterPort = options.port
this.password = options.password
this.onConnect = options.onConnect
this.autoReconnect = true
if (options.reconnectInterval === 0) {
this.autoReconnect = false
}
this.log = console.log
if (options.verbose === false) {
this.log = () => {}
}
this.reconnectInterval = options.reconnectInterval || 5000
this.socket = null
this.connect()
}
Connector.prototype.connect = function() {
this.socket = new net.Socket()
this.socket.connect(this.masterPort, this.masterIP, () => {
this.log(`Connector reached ${this.masterIP}:${this.masterPort}`)
this.send({ password: this.password })
if (typeof this.onConnect === 'function') {
this.onConnect()
}
})
this.socket.on('close', () => {
this.socket = null
this.log('MasterServer connection closed')
if (this.autoReconnect) {
setTimeout(() => {
this.log('Retrying MasterServer connection...')
this.connect()
}, this.reconnectInterval)
}
})
this.socket.on('error', error => {
this.log('MasterServer connection error', error)
this.socket.destroy()
this.socket.unref()
})
}
Connector.prototype.send = function(message) {
if (this.socket !== null) {
this.socket.write(JSON.stringify(message) + '\n')
}
}
module.exports = Connector