* Open a new socket and try to connect again. * * @param count Number of current retries
(count = 1)
| 106 | * @param count Number of current retries |
| 107 | */ |
| 108 | async reconnect(count = 1): Promise<void> { |
| 109 | if (this.keepOpen) { |
| 110 | // Disconnect |
| 111 | if (this.client.socket) { |
| 112 | console.log('Closing existing connection...'); |
| 113 | this.client.socket.close(); |
| 114 | this.client.socket = undefined; |
| 115 | } |
| 116 | |
| 117 | if (this.url) { |
| 118 | // Connect |
| 119 | console.log(`Reconnecting to ${this.url} - Attempt ${count}`); |
| 120 | return SocketClient.connect(this.socketCon, this.url, this.secret) |
| 121 | .then(socket => { |
| 122 | this.setSocket(socket); |
| 123 | if (this.onStateChange) { |
| 124 | this.onStateChange(true); |
| 125 | } |
| 126 | }) |
| 127 | .catch(async (error) => { |
| 128 | if (count < 5) { |
| 129 | console.error(`Failed Connection Attempt: ${error}`); |
| 130 | await new Promise<void>(resolve => { |
| 131 | setTimeout(resolve, 2000); |
| 132 | }); |
| 133 | return this.reconnect(count + 1); |
| 134 | } else { |
| 135 | console.error(`Reconnecting failed ${count} times, please restart the application.`); |
| 136 | if (this.onFatal) { |
| 137 | this.onFatal(); |
| 138 | } |
| 139 | } |
| 140 | }); |
| 141 | } else { |
| 142 | console.error('No client url stored, cannot reconnect (Is this a host?)'); |
| 143 | } |
| 144 | } |
| 145 | } |
| 146 | |
| 147 | private ensureConnection() { |
| 148 | if (this.keepOpen) { |