-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
164 lines (135 loc) · 3.65 KB
/
server.js
File metadata and controls
164 lines (135 loc) · 3.65 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
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
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
let WebSocketServer = require('ws').Server
let fs = require("fs")
let stocks
try {
stocks = JSON.parse(fs.readFileSync("stocks.json"))
console.log("Successfully loaded stocks data.")
} catch {
throw Error("Could not load stocks data.")
}
let stockSymbols = stocks.map(stock => stock.symbol)
console.log(`Supported stock symbols: ${stockSymbols}`)
let wss = new WebSocketServer({port: 8080})
console.log("WebSocket server is listening on port 8080.")
let getConnectedEvent = () => {
let event = {
event: "connected",
supportedSymbols: stockSymbols,
message: "All stocks data is not real and is generated solely for demo purposes."
}
return JSON.stringify(event)
}
let getDisconnectingEvent = (reason) => {
let event = {
event: "disconnecting",
reason: reason
}
return JSON.stringify(event)
}
let getErrorEvent = (reason) => {
let event = {
event: "error",
reason: reason
}
return JSON.stringify(event)
}
let getStocksUpdateEvent = (connectionInfo) => {
let event = {
event: "stocks-update",
stocks: {}
}
connectionInfo.stocksToWatch.forEach(stock => {
let stockInfo = stocks.find(e => e.symbol === stock)
if (stockInfo) {
let priceDataLength = stockInfo.priceData.length
if (connectionInfo.stocksUpdateCount >= priceDataLength) {
connectionInfo.stocksUpdateCount = 0
}
event.stocks[stock] = stockInfo.priceData[connectionInfo.stocksUpdateCount].price
}
})
return JSON.stringify(event)
}
let disconnect = (ws, reason) => {
ws.send(getDisconnectingEvent(reason))
ws.terminate()
}
let handleSubscribe = (ws, parsedMessage, connectionInfo) => {
if (parsedMessage.stocks instanceof Array) {
parsedMessage.stocks.forEach(stock => {
if (stocks.some(e => e.symbol === stock)) {
if (!connectionInfo.stocksToWatch.includes(stock)) {
connectionInfo.stocksToWatch.push(stock)
}
} else {
ws.send(getErrorEvent("invalid stock symbol"))
}
})
} else {
ws.send(getErrorEvent("invalid message"))
}
}
let handleUnsubscribe = (ws, parsedMessage, connectionInfo) => {
if (parsedMessage.stocks instanceof Array) {
parsedMessage.stocks.forEach(stock => {
let i = connectionInfo.stocksToWatch.indexOf(stock)
if (i > -1) {
connectionInfo.stocksToWatch.splice(i, 1)
}
})
} else {
ws.send(getErrorEvent("invalid message"))
}
}
wss.on('connection', (ws) => {
ws.send(getConnectedEvent())
let connectionInfo = {
isActive: true,
stocksToWatch: [],
stocksUpdateCount: 0
}
ws.pingInterval = setInterval(() => {
if (!connectionInfo.isActive) {
disconnect(ws, "connection inactive")
} else {
connectionInfo.isActive = false
ws.ping()
}
}, 15000)
ws.stocksInterval = setInterval(() => {
if (connectionInfo.stocksToWatch.length > 0) {
ws.send(getStocksUpdateEvent(connectionInfo))
connectionInfo.stocksUpdateCount += 1
}
}, 10000)
ws.connectionTimeout = setTimeout(() => {
disconnect(ws, "connection time exceeds 5 minutes")
}, 300000)
ws.on('message', (message) => {
connectionInfo.isActive = true
if (message.length > 300) {
ws.send(getErrorEvent("message too long"))
return
}
let parsedMessage
try {
parsedMessage = JSON.parse(message)
} catch {
ws.send(getErrorEvent("invalid message"))
return
}
if (parsedMessage.event === "subscribe") {
handleSubscribe(ws, parsedMessage, connectionInfo)
} else if (parsedMessage.event === "unsubscribe") {
handleUnsubscribe(ws, parsedMessage, connectionInfo)
}
})
ws.on('close', () => {
clearInterval(ws.pingInterval)
clearInterval(ws.stocksInterval)
clearTimeout(ws.connectionTimeout)
})
ws.on('pong', () => {
connectionInfo.isActive = true
});
})