1 |
|
2 | const WebSocket = require('ws')
|
3 | const Hookable = require('hookable')
|
4 |
|
5 | class WS extends Hookable {
|
6 | constructor (options) {
|
7 | super()
|
8 | this.wss = new WebSocket.Server({ noServer: true })
|
9 | this.hook('upgrade', (request, socket, head) => {
|
10 | if (request.url === `/${options.apiPrefix}/ws`) {
|
11 | this.handleUpgrade(request, socket, head)
|
12 | }
|
13 | })
|
14 | }
|
15 |
|
16 | serve (req) {
|
17 | this.handleUpgrade(req, req.socket, undefined)
|
18 | }
|
19 |
|
20 | handleUpgrade (request, socket, head = '') {
|
21 | return this.wss.handleUpgrade(request, socket, head, (client) => {
|
22 | this.wss.emit('connection', client, request)
|
23 | })
|
24 | }
|
25 |
|
26 | |
27 |
|
28 |
|
29 |
|
30 | broadcast (data) {
|
31 | data = JSON.stringify(data)
|
32 |
|
33 | for (const client of this.wss.clients) {
|
34 | try {
|
35 | client.send(data)
|
36 | } catch (err) {
|
37 |
|
38 | }
|
39 | }
|
40 | }
|
41 | }
|
42 |
|
43 | module.exports = WS
|