-
Notifications
You must be signed in to change notification settings - Fork 1
/
browser.js
46 lines (43 loc) · 1.19 KB
/
browser.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
const Base = require('./base')
class WSClient extends Base {
constructor (endpoint, options = {}) {
super(options)
this.client = new WebSocket(endpoint, 'fast-ws')
this.client.onerror = error => {
super.emit('error', error)
}
this.client.onopen = () => {
this.connectState = 1
super.emit('open')
this._heartbeat = setInterval(() => {
this.ping()
}, this.options.pingInterval)
}
this.client.onclose = () => {
super.emit('close')
this.connectState = -1
clearInterval(this._heartbeat)
super.emit('disconnect')
}
this.client.onmessage = ({ type, data }) => {
if (this.connectState !== 2) {
if (data === '\x00\x02') {
this.connectState = 2
super.emit('connect')
} else {
super.emit('error', new Error('Server version mismatch.'))
}
} else {
this.incomingPacket(data)
}
}
}
ping () {
const autoTerminate = setTimeout(() => this.client.close(), this.options.pingTimeout)
this.client.send(Base.getPayload(null, 'ping'))
super.once('pong', () => {
clearTimeout(autoTerminate)
})
}
}
module.exports = WSClient