-
Notifications
You must be signed in to change notification settings - Fork 582
/
Upgrade.js
51 lines (47 loc) · 1.49 KB
/
Upgrade.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
/* A quite detailed WebSockets example */
const uWS = require('../dist/uws.js');
const port = 9001;
const app = uWS./*SSL*/App({
key_file_name: 'misc/key.pem',
cert_file_name: 'misc/cert.pem',
passphrase: '1234'
}).ws('/*', {
/* Options */
compression: uWS.SHARED_COMPRESSOR,
maxPayloadLength: 16 * 1024 * 1024,
idleTimeout: 10,
/* Handlers */
upgrade: (res, req, context) => {
console.log('An Http connection wants to become WebSocket, URL: ' + req.getUrl() + '!');
/* This immediately calls open handler, you must not use res after this call */
res.upgrade({
myData: req.getUrl() /* First argument is UserData (see WebSocket.getUserData()) */
},
/* Spell these correctly */
req.getHeader('sec-websocket-key'),
req.getHeader('sec-websocket-protocol'),
req.getHeader('sec-websocket-extensions'),
context);
},
open: (ws) => {
console.log('A WebSocket connected with URL: ' + ws.myData);
},
message: (ws, message, isBinary) => {
/* Ok is false if backpressure was built up, wait for drain */
let ok = ws.send(message, isBinary);
},
drain: (ws) => {
console.log('WebSocket backpressure: ' + ws.getBufferedAmount());
},
close: (ws, code, message) => {
console.log('WebSocket closed');
}
}).any('/*', (res, req) => {
res.end('Nothing to see here!');
}).listen(port, (token) => {
if (token) {
console.log('Listening to port ' + port);
} else {
console.log('Failed to listen to port ' + port);
}
});