|
| 1 | +/* A quite detailed WebSockets upgrade example "async" */ |
| 2 | + |
| 3 | +const uWS = require('../dist/uws.js'); |
| 4 | +const port = 9001; |
| 5 | + |
| 6 | +const app = uWS./*SSL*/App({ |
| 7 | + key_file_name: 'misc/key.pem', |
| 8 | + cert_file_name: 'misc/cert.pem', |
| 9 | + passphrase: '1234' |
| 10 | +}).ws('/*', { |
| 11 | + /* Options */ |
| 12 | + compression: uWS.SHARED_COMPRESSOR, |
| 13 | + maxPayloadLength: 16 * 1024 * 1024, |
| 14 | + idleTimeout: 10, |
| 15 | + /* Handlers */ |
| 16 | + upgrade: (res, req, context) => { |
| 17 | + console.log('An Http connection wants to become WebSocket, URL: ' + req.getUrl() + '!'); |
| 18 | + |
| 19 | + /* Keep track of abortions */ |
| 20 | + const upgradeAborted = {aborted: false}; |
| 21 | + |
| 22 | + /* You MUST copy data out of req here, as req is only valid within this immediate callback */ |
| 23 | + const url = req.getUrl(); |
| 24 | + const secWebSocketKey = req.getHeader('sec-websocket-key'); |
| 25 | + const secWebSocketProtocol = req.getHeader('sec-websocket-protocol'); |
| 26 | + const secWebSocketExtensions = req.getHeader('sec-websocket-extensions'); |
| 27 | + |
| 28 | + /* Simulate doing "async" work before upgrading */ |
| 29 | + setTimeout(() => { |
| 30 | + console.log("We are now done with our async task, let's upgrade the WebSocket!"); |
| 31 | + |
| 32 | + if (upgradeAborted.aborted) { |
| 33 | + console.log("Ouch! Client disconnected before we could upgrade it!"); |
| 34 | + /* You must not upgrade now */ |
| 35 | + return; |
| 36 | + } |
| 37 | + |
| 38 | + /* This immediately calls open handler, you must not use res after this call */ |
| 39 | + res.upgrade({ |
| 40 | + url: url |
| 41 | + }, |
| 42 | + /* Use our copies here */ |
| 43 | + secWebSocketKey, |
| 44 | + secWebSocketProtocol, |
| 45 | + secWebSocketExtensions, |
| 46 | + context); |
| 47 | + }, 1000); |
| 48 | + |
| 49 | + /* You MUST register an abort handler to know if the upgrade was aborted by peer */ |
| 50 | + res.onAborted(() => { |
| 51 | + /* We can simply signal that we were aborted */ |
| 52 | + upgradeAborted.aborted = true; |
| 53 | + }); |
| 54 | + }, |
| 55 | + open: (ws) => { |
| 56 | + console.log('A WebSocket connected with URL: ' + ws.url); |
| 57 | + }, |
| 58 | + message: (ws, message, isBinary) => { |
| 59 | + /* Ok is false if backpressure was built up, wait for drain */ |
| 60 | + let ok = ws.send(message, isBinary); |
| 61 | + }, |
| 62 | + drain: (ws) => { |
| 63 | + console.log('WebSocket backpressure: ' + ws.getBufferedAmount()); |
| 64 | + }, |
| 65 | + close: (ws, code, message) => { |
| 66 | + console.log('WebSocket closed'); |
| 67 | + } |
| 68 | +}).any('/*', (res, req) => { |
| 69 | + res.end('Nothing to see here!'); |
| 70 | +}).listen(port, (token) => { |
| 71 | + if (token) { |
| 72 | + console.log('Listening to port ' + port); |
| 73 | + } else { |
| 74 | + console.log('Failed to listen to port ' + port); |
| 75 | + } |
| 76 | +}); |
0 commit comments