Skip to content

Commit a01c640

Browse files
committed
feat: enhance HonoHttpServer listen method with port retry logic and logging
1 parent d0200d0 commit a01c640

2 files changed

Lines changed: 38 additions & 11 deletions

File tree

packages/plugins/plugin-hono-server/src/adapter.ts

Lines changed: 31 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -113,19 +113,43 @@ export class HonoHttpServer implements IHttpServer {
113113

114114

115115
async listen(port: number) {
116-
return new Promise<void>((resolve) => {
117-
if (this.staticRoot) {
118-
this.app.get('/*', serveStatic({ root: this.staticRoot }));
116+
if (this.staticRoot) {
117+
this.app.get('/*', serveStatic({ root: this.staticRoot }));
118+
}
119+
120+
const targetPort = port || this.port;
121+
const maxRetries = 20;
122+
123+
for (let attempt = 0; attempt < maxRetries; attempt++) {
124+
const tryPort = targetPort + attempt;
125+
try {
126+
await this.tryListen(tryPort);
127+
return;
128+
} catch (err: any) {
129+
if (err.code === 'EADDRINUSE' && attempt < maxRetries - 1) {
130+
if (this.server && typeof this.server.close === 'function') {
131+
this.server.close();
132+
}
133+
continue;
134+
}
135+
throw err;
119136
}
120-
121-
const targetPort = port || this.port;
122-
this.server = serve({
137+
}
138+
}
139+
140+
private tryListen(port: number): Promise<void> {
141+
return new Promise<void>((resolve, reject) => {
142+
const server = serve({
123143
fetch: this.app.fetch,
124-
port: targetPort
144+
port
125145
}, (info) => {
126146
this.listeningPort = info.port;
127147
resolve();
128148
});
149+
this.server = server;
150+
server.on('error', (err: any) => {
151+
reject(err);
152+
});
129153
});
130154
}
131155

packages/plugins/plugin-hono-server/src/hono-plugin.ts

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -234,11 +234,14 @@ export class HonoServerPlugin implements Plugin {
234234
ctx.logger.debug('Starting HTTP server', { port });
235235

236236
await this.server.listen(port);
237-
237+
238238
const actualPort = this.server.getPort();
239-
ctx.logger.info('HTTP server started successfully', {
240-
port: actualPort,
241-
url: `http://localhost:${actualPort}`
239+
if (actualPort !== port) {
240+
ctx.logger.warn(`Port ${port} is in use, using port ${actualPort} instead`);
241+
}
242+
ctx.logger.info('HTTP server started successfully', {
243+
port: actualPort,
244+
url: `http://localhost:${actualPort}`
242245
});
243246
});
244247
}

0 commit comments

Comments
 (0)