(timeout = (1000 * 60 * 5))
| 24 | |
| 25 | // Default wait time is about 5 minutes |
| 26 | public start(timeout = (1000 * 60 * 5)): Promise<void> { |
| 27 | let retry = true; |
| 28 | const start = Date.now(); |
| 29 | const obj = parseHostPort(this.tcpPort); |
| 30 | return new Promise((resolve, reject) => { |
| 31 | this.timer = setInterval(() => { |
| 32 | if (!retry) { |
| 33 | // Last attempt is still ongoing. It hasn't failed or succeeded |
| 34 | return; |
| 35 | } |
| 36 | retry = false; |
| 37 | this.client = net.createConnection(obj, () => { |
| 38 | clearInterval(this.timer); |
| 39 | this.timer = undefined; |
| 40 | this.connected = true; |
| 41 | this.emit('connected'); |
| 42 | console.log(`Connected SWO/RTT port ${this.tcpPort}, nTries = ${this.nTries}\n`); |
| 43 | resolve(); |
| 44 | }); |
| 45 | this.client.on('data', (buffer) => { |
| 46 | this.processData(buffer); |
| 47 | }); |
| 48 | this.client.on('end', () => { |
| 49 | this.dispose(); |
| 50 | }); |
| 51 | this.client.on('close', () => { |
| 52 | // This can happen because we are destroying ourselves although we never |
| 53 | // got connected.... the retry timer may still be running. |
| 54 | this.disposeClient(); |
| 55 | }); |
| 56 | this.client.on('error', (e) => { |
| 57 | const code: string = (e as any).code; |
| 58 | if ((code === 'ECONNRESET') && this.connected) { |
| 59 | // Server closed the connection. Done with this session, not in the normal way but we are done. |
| 60 | // Lot of people have issues on what to expect events end/close/error(ECONNRESET). Protect against |
| 61 | // all of them. This problem is wideley seen in various versions of NODE and OS dependent and not |
| 62 | // sure which doc/webpage/blog is the authoritative thing here. |
| 63 | this.dispose(); |
| 64 | } else if (code === 'ECONNREFUSED') { |
| 65 | // We expect 'ECONNREFUSED' if the server has not yet started. |
| 66 | const delta = Date.now() - start; |
| 67 | if (delta > timeout) { |
| 68 | (e as any).message = `Error: Failed to connect to port ${this.tcpPort} ${code}`; |
| 69 | console.log(`Failed ECONNREFUSED SWO/RTT port ${this.tcpPort}, nTries = ${this.nTries}`); |
| 70 | this.connError = e; |
| 71 | this.emit('error', e); |
| 72 | reject(e); |
| 73 | this.dispose(); |
| 74 | } else { |
| 75 | if ((this.nTries % 10) === 0) { |
| 76 | console.log(`Trying SWO/RTT port ${this.tcpPort}, nTries = ${this.nTries}`); |
| 77 | } |
| 78 | retry = true; |
| 79 | this.nTries++; |
| 80 | this.disposeClient(); |
| 81 | } |
| 82 | } else { |
| 83 | (e as any).message = `Error: Ignored unknown error on port ${this.tcpPort} ${code}`; |
nothing calls this directly
no test coverage detected