-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
76 lines (68 loc) · 2.21 KB
/
index.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
import uWS from 'uWebSockets.js'
import { ChatServer } from './src/ChatServer.js'
import {
messageTypesStr,
errorsStr,
decodeMessageHeader, encodeMessage
} from './src/specs.js'
import { generateConfig } from "./config.js"
let configName
if (process.env.PICTOCLONE_SERVER_CONFIG_NAME) {
configName = process.env.PICTOCLONE_SERVER_CONFIG_NAME
}
if (configName == null) {
configName = 'production'
}
const config = generateConfig(uWS, configName)
if (config === null) {
console.error('Could not find a valid configuration for name ' + configName)
process.ext(1)
}
console.log('Initializing server with config ' + configName)
const port = config.port
global.debug = config.debug
const chatServer = new ChatServer()
const app = uWS[config.ssl ? 'SSLApp' : 'App' ](
config.sslParams
).ws('/*', {
/* Options */
...config.uwsParams,
/* Handlers */
open: (ws) => {
const response = chatServer.addNewConnection(ws)
let ok = ws.send(encodeMessage(response), true)
},
message: (ws, payload, isBinary) => {
try {
const { message, payloadOffset } = decodeMessageHeader(payload)
let response = chatServer.handleIncomingMessage(message, payload, payloadOffset, ws)
if (response != null) {
// Ok is false if backpressure was built up, wait for drain
let ok = ws.send(encodeMessage(response), isBinary);
}
} catch (e) {
global.debug && console.error('uWS.message: general error caught when processing a message:', e)
const response = {
type: messageTypesStr.get('MSG_TYPE_GENERIC_ERROR'),
uniqueId: ws.uniqueId != null ? ws.uniqueId : 0,
errorCode: errorsStr.get('ERROR_GENERIC_ERROR'),
errorMessage: debug ? e.toString() : 'Generic error'
}
let ok = ws.send(encodeMessage(response), isBinary);
}
},
drain: (ws) => {
global.debug && console.log('uWS.drain WebSocket backpressure: ' + ws.getBufferedAmount());
},
close: (ws, code, message) => {
chatServer.closeConnection(ws)
}
}).any('/*', (res, req) => {
res.end('<>');
}).listen(port, (token) => {
if (token) {
console.log('uWS.listen: Listening to port ' + port);
} else {
console.log('uWS.listen: Failed to listen to port ' + port);
}
});