| 37 | } |
| 38 | |
| 39 | onConnection (ws, request) { |
| 40 | |
| 41 | console.log (new Date (), 'onConnection') |
| 42 | |
| 43 | // terminate any incoming connection |
| 44 | // immediately after it has been successfully established |
| 45 | if (Number.isInteger (this.terminateTimeout)) { |
| 46 | if (this.terminateTimeout) { |
| 47 | setTimeout (() => { ws.terminate () }, this.terminateTimeout) |
| 48 | } else { |
| 49 | ws.terminate () |
| 50 | } |
| 51 | } |
| 52 | |
| 53 | // close the connection after a certain amount of time |
| 54 | if (Number.isInteger (this.closeTimeout)) { |
| 55 | if (this.closeTimeout) { |
| 56 | setTimeout (() => { |
| 57 | console.log (new Date (), 'Closing with code', this.closeCode, typeof this) |
| 58 | // ws.terminate () |
| 59 | ws.close (this.closeCode) |
| 60 | }, this.closeTimeout) |
| 61 | } else { |
| 62 | ws.close (this.closeCode) |
| 63 | } |
| 64 | } |
| 65 | |
| 66 | // error the connection after a certain amount of time |
| 67 | if (Number.isInteger (this.errorTimeout)) { |
| 68 | if (this.errorTimeout) { |
| 69 | setTimeout (() => { |
| 70 | console.log (new Date (), 'Closing with code', this.errorTimeout, typeof this) |
| 71 | // ws.terminate () |
| 72 | this.error (ws) |
| 73 | }, this.errorTimeout) |
| 74 | } else { |
| 75 | this.error (ws) |
| 76 | } |
| 77 | } |
| 78 | |
| 79 | // ws.send ('something') |
| 80 | |
| 81 | // other stuff that might be useful |
| 82 | ws.on ('message', function incoming (message) { |
| 83 | console.log (new Date (), 'onMessage', message) |
| 84 | if (message === 'error') { |
| 85 | invalidFrame (ws) |
| 86 | } else if (message === 'close') { |
| 87 | ws.close (this.closeCode) |
| 88 | } else { |
| 89 | // echo back |
| 90 | ws.send (message) |
| 91 | } |
| 92 | }) |
| 93 | ws.on ('ping', (message) => { |
| 94 | console.log (new Date (), 'onPing', message.toString ()) |
| 95 | // ws.pong () // ws sends pong automatically |
| 96 | }) |