-
-
Notifications
You must be signed in to change notification settings - Fork 116
/
server.js
executable file
·139 lines (128 loc) · 3.44 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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
#!/usr/bin/env node
import { WebSocketServer } from 'ws'
import http from 'http'
import * as map from 'lib0/map'
const wsReadyStateConnecting = 0
const wsReadyStateOpen = 1
const wsReadyStateClosing = 2 // eslint-disable-line
const wsReadyStateClosed = 3 // eslint-disable-line
const pingTimeout = 30000
const port = process.env.PORT || 4444
const wss = new WebSocketServer({ noServer: true })
const server = http.createServer((request, response) => {
response.writeHead(200, { 'Content-Type': 'text/plain' })
response.end('okay')
})
/**
* Map froms topic-name to set of subscribed clients.
* @type {Map<string, Set<any>>}
*/
const topics = new Map()
/**
* @param {any} conn
* @param {object} message
*/
const send = (conn, message) => {
if (conn.readyState !== wsReadyStateConnecting && conn.readyState !== wsReadyStateOpen) {
conn.close()
}
try {
conn.send(JSON.stringify(message))
} catch (e) {
conn.close()
}
}
/**
* Setup a new client
* @param {any} conn
*/
const onconnection = conn => {
/**
* @type {Set<string>}
*/
const subscribedTopics = new Set()
let closed = false
// Check if connection is still alive
let pongReceived = true
const pingInterval = setInterval(() => {
if (!pongReceived) {
conn.close()
clearInterval(pingInterval)
} else {
pongReceived = false
try {
conn.ping()
} catch (e) {
conn.close()
}
}
}, pingTimeout)
conn.on('pong', () => {
pongReceived = true
})
conn.on('close', () => {
subscribedTopics.forEach(topicName => {
const subs = topics.get(topicName) || new Set()
subs.delete(conn)
if (subs.size === 0) {
topics.delete(topicName)
}
})
subscribedTopics.clear()
closed = true
})
conn.on('message', /** @param {object} message */ message => {
if (typeof message === 'string' || message instanceof Buffer) {
message = JSON.parse(message)
}
if (message && message.type && !closed) {
switch (message.type) {
case 'subscribe':
/** @type {Array<string>} */ (message.topics || []).forEach(topicName => {
if (typeof topicName === 'string') {
// add conn to topic
const topic = map.setIfUndefined(topics, topicName, () => new Set())
topic.add(conn)
// add topic to conn
subscribedTopics.add(topicName)
}
})
break
case 'unsubscribe':
/** @type {Array<string>} */ (message.topics || []).forEach(topicName => {
const subs = topics.get(topicName)
if (subs) {
subs.delete(conn)
}
})
break
case 'publish':
if (message.topic) {
const receivers = topics.get(message.topic)
if (receivers) {
message.clients = receivers.size
receivers.forEach(receiver =>
send(receiver, message)
)
}
}
break
case 'ping':
send(conn, { type: 'pong' })
}
}
})
}
wss.on('connection', onconnection)
server.on('upgrade', (request, socket, head) => {
// You may check auth of request here..
/**
* @param {any} ws
*/
const handleAuth = ws => {
wss.emit('connection', ws, request)
}
wss.handleUpgrade(request, socket, head, handleAuth)
})
server.listen(port)
console.log('Signaling server running on localhost:', port)