From 98023eab53b69a50933cf683b239e84e79378383 Mon Sep 17 00:00:00 2001 From: Nisarg Jhaveri Date: Tue, 7 Jan 2025 00:21:34 +0530 Subject: [PATCH] Attempt to reuse the same port for the server --- src/extension.ts | 54 +++++++++++++++++++++++++++++++++++------------- 1 file changed, 40 insertions(+), 14 deletions(-) diff --git a/src/extension.ts b/src/extension.ts index b29dd98..aab937d 100644 --- a/src/extension.ts +++ b/src/extension.ts @@ -7,22 +7,48 @@ import { logger } from './logger'; let server: Server|undefined = undefined; let serverUri: vscode.Uri|undefined = undefined; +async function startServerAtPort(context: vscode.ExtensionContext, port: number): Promise { + server = new Server( + { + port: port, + host: "127.0.0.1" + }, + /* httpsOptions */ undefined, + { + staticClientPath: vscode.Uri.joinPath(context.extensionUri, "dist/web").fsPath, + } + ); + + serverUri = vscode.Uri.parse(await server.start()); + return serverUri; +} + async function ensureServerListening(context: vscode.ExtensionContext) { - if (!server) { - server = new Server( - { - port: 0, - host: "127.0.0.1" - }, - /* httpsOptions */ undefined, - { - staticClientPath: vscode.Uri.joinPath(context.extensionUri, "dist/web").fsPath, - } - ); - } + if (!(server && server.isListening())) { + let port: number = 44615; + let remainingAttempts = 5; + + while (remainingAttempts > 0) { + remainingAttempts--; - if (!server.isListening()) { - serverUri = vscode.Uri.parse(await server.start()); + try { + await startServerAtPort(context, port); + break; + } catch (e: any) { + if (e.code === "EADDRINUSE" && remainingAttempts > 0) { + logger.info(`Port ${port} is already in use, trying another port...`); + if (remainingAttempts === 1) { + // Try random port on the last attempt + port = 0; + } else { + port++; + } + } else { + logger.error(`Failed to start server: ${e.message}`); + throw e; + } + } + } } }