-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathserver.js
More file actions
81 lines (65 loc) · 1.9 KB
/
Copy pathserver.js
File metadata and controls
81 lines (65 loc) · 1.9 KB
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
const { createServer } = require('http')
const { parse } = require('url')
const next = require('next')
const { WebSocketServer } = require('ws')
const dev = process.env.NODE_ENV !== 'production'
const hostname = 'localhost'
const port = 3000
const app = next({ dev, hostname, port })
const handle = app.getRequestHandler()
let wss = null
const clients = new Map()
app.prepare().then(() => {
const server = createServer(async (req, res) => {
try {
const parsedUrl = parse(req.url, true)
await handle(req, res, parsedUrl)
} catch (err) {
console.error('Error occurred handling', req.url, err)
res.statusCode = 500
res.end('internal server error')
}
})
wss = new WebSocketServer({ noServer: true })
wss.on('connection', (ws) => {
clients.set(ws, new Set())
ws.on('message', (data) => {
try {
const message = JSON.parse(data.toString())
if (message.type === 'subscribe' && message.channelId) {
const channels = clients.get(ws)
if (channels) {
channels.add(message.channelId)
}
}
} catch (error) {}
})
ws.on('close', () => {
clients.delete(ws)
})
ws.on('error', () => {})
})
server.on('upgrade', (request, socket, head) => {
const { pathname } = parse(request.url)
if (pathname === '/ws') {
wss.handleUpgrade(request, socket, head, (ws) => {
wss.emit('connection', ws, request)
})
} else {
socket.destroy()
}
})
server.listen(port, (err) => {
if (err) throw err
console.log(`> Ready on http://${hostname}:${port}`)
})
global.broadcastMessage = (channelId, data) => {
if (!wss) return
const message = JSON.stringify(data)
clients.forEach((subscribedChannels, ws) => {
if (subscribedChannels.has(channelId) && ws.readyState === 1) {
ws.send(message)
}
})
}
})