-
Notifications
You must be signed in to change notification settings - Fork 1
/
node.js
56 lines (53 loc) · 1.49 KB
/
node.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
const Base = require('./base')
const WebSocket = require('ws')
class WSClient extends Base {
constructor (endpoint, options = {}) {
super(options)
this.client = new WebSocket(endpoint, 'fast-ws', options)
this.client.on('error', error => {
super.emit('error', error)
})
this.client.on('open', () => {
this.connectState = 1
this._heartbeat = setInterval(() => {
this.ping()
}, this.options.pingInterval)
})
this.client.on('close', () => {
this.connectState = -1
clearInterval(this._heartbeat)
super.emit('disconnect')
})
this.client.on('message', (message, isBinary) => {
if (!isBinary) message = message.toString()
if (this.connectState !== 2) {
if (message === '\x00\x02') {
this.connectState = 2
super.emit('connect')
} else {
super.emit('error', new Error('Server version mismatch.'))
}
} else {
this.incomingPacket(message)
}
})
this.client.on('ping', () => {
super.emit('ping')
})
this.client.on('pong', (data) => {
if (data.length) {
super.emit('pong', new Date().valueOf() - data.toString())
} else {
super.emit('pong')
}
})
}
ping () {
const autoTerminate = setTimeout(() => this.client.terminate(), this.options.pingTimeout)
this.client.ping(new Date().valueOf())
super.once('pong', () => {
clearTimeout(autoTerminate)
})
}
}
module.exports = WSClient