| 40 | const MAX_RETRIES = 5; |
| 41 | |
| 42 | export class SocketServer { |
| 43 | api: BackAPI = create_api(); |
| 44 | clients: BackClients = create_server(); |
| 45 | |
| 46 | retryCounter = 0; |
| 47 | |
| 48 | /** Underlying WebSocket server. */ |
| 49 | server?: ws.Server; |
| 50 | /** Chosen host */ |
| 51 | host: string | undefined = undefined; |
| 52 | /** Port the server is listening on (-1 if not listening). */ |
| 53 | port = -1; |
| 54 | /** Secret value used for authentication. */ |
| 55 | secret: any; |
| 56 | |
| 57 | /** Middleware for BackOut responses */ |
| 58 | middlewareRes: PipelineRes = genPipelineBackOut(); |
| 59 | |
| 60 | /** Queues for incoming requests. */ |
| 61 | queues: RequestQueue[] = []; |
| 62 | |
| 63 | lastClient?: BackClient; |
| 64 | |
| 65 | /** |
| 66 | * Try to listen on one of the ports in the given range (starting from the lowest). |
| 67 | * If it succeeds it will set the "server" and "port" properties of this object. |
| 68 | * If it fails it will reject with the error. |
| 69 | * |
| 70 | * @param minPort Minimum port number (tried first). |
| 71 | * @param maxPort Maximum port number (tried last). |
| 72 | * @param host Server host (determines what clients can connect). |
| 73 | */ |
| 74 | public async listen(minPort: number, maxPort: number, host: string | undefined): Promise<void> { |
| 75 | this.host = host; |
| 76 | const result = await startServer(this.port !== -1 ? this.port : minPort, this.port !== -1 ? this.port : maxPort, host); |
| 77 | result.server.on('connection', this.onConnect.bind(this)); |
| 78 | this.server = result.server; |
| 79 | this.port = result.port; |
| 80 | this.retryCounter = 0; // Reset retries on a good connection |
| 81 | this.server.on('error', this.onError); |
| 82 | } |
| 83 | |
| 84 | onError(err: Error) { |
| 85 | if (this.retryCounter < MAX_RETRIES) { |
| 86 | if (this.server) { // Try and close / remove server first |
| 87 | try { |
| 88 | this.server.close(); |
| 89 | } catch {/** Ignore closure errors */} finally { |
| 90 | this.server = undefined; |
| 91 | } |
| 92 | } |
| 93 | this.retryCounter++; |
| 94 | setTimeout(() => { // Sleep then try and connect again |
| 95 | this.listen(0,0, this.host) |
| 96 | .catch(this.onError); // If failed to open, keep trying until we get there! |
| 97 | }, 1500); |
| 98 | } |
| 99 | } |
nothing calls this directly
no test coverage detected