forked from feross/simple-websocket
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
60 lines (47 loc) · 1.39 KB
/
server.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
59
60
const events = require('events')
const Socket = require('./')
const WebSocketServer = require('ws').Server
class SocketServer extends events.EventEmitter {
constructor (opts) {
super()
this.opts = {
clientTracking: false,
perMessageDeflate: false,
...opts
}
this.destroyed = false
this._server = new WebSocketServer(this.opts)
this._server.on('listening', this._handleListening)
this._server.on('connection', this._handleConnection)
this._server.once('error', this._handleError)
}
address () {
return this._server.address()
}
close (cb) {
if (this.destroyed) {
if (cb) cb(new Error('server is closed'))
return
}
this.destroyed = true
if (cb) this.once('close', cb)
this._server.removeListener('listening', this._handleListening)
this._server.removeListener('connection', this._handleConnection)
this._server.removeListener('error', this._handleError)
this._server.on('error', () => {}) // suppress future errors
this._server.close(() => this.emit('close'))
this._server = null
}
_handleListening = () => {
this.emit('listening')
}
_handleConnection = (conn, req) => {
const socket = new Socket({ ...this.opts, socket: conn })
this.emit('connection', socket, req)
}
_handleError = (err) => {
this.emit('error', err)
this.close()
}
}
module.exports = SocketServer