Unverified Commit 45515716 authored by Yunfei He's avatar Yunfei He Committed by GitHub

Automatically use different port to start dev server for non-explicit port (#30736)

* Automatically using different port to start dev server for non-explicit port

* return correct port

* more reasonable changes

* fix isExplicitPort

* 1. rename isExplicitPort to allowRetry 2.restrict the number of retries
Co-authored-by: 's avatarSteven <steven@ceriously.com>
parent 0c04f96e
...@@ -73,7 +73,7 @@ const nextDev: cliCommand = (argv) => { ...@@ -73,7 +73,7 @@ const nextDev: cliCommand = (argv) => {
) )
} }
} }
const allowRetry = !args['--port']
let port: number = let port: number =
args['--port'] || (process.env.PORT && parseInt(process.env.PORT)) || 3000 args['--port'] || (process.env.PORT && parseInt(process.env.PORT)) || 3000
...@@ -88,7 +88,11 @@ const nextDev: cliCommand = (argv) => { ...@@ -88,7 +88,11 @@ const nextDev: cliCommand = (argv) => {
// some set-ups that rely on listening on other interfaces // some set-ups that rely on listening on other interfaces
const host = args['--hostname'] const host = args['--hostname']
startServer({ dir, dev: true, isNextDevCommand: true }, port, host) startServer(
{ dir, dev: true, isNextDevCommand: true, allowRetry },
port,
host
)
.then(async ({ app, actualPort }) => { .then(async ({ app, actualPort }) => {
const appUrl = `http://${ const appUrl = `http://${
!host || host === '0.0.0.0' ? 'localhost' : host !host || host === '0.0.0.0' ? 'localhost' : host
......
import http from 'http' import http from 'http'
import next from '../next' import next from '../next'
import { warn } from '../../build/output/log'
export default async function start( export default async function start(
serverOptions: any, serverOptions: any,
...@@ -18,8 +19,23 @@ export default async function start( ...@@ -18,8 +19,23 @@ export default async function start(
requestHandler = app.getRequestHandler() requestHandler = app.getRequestHandler()
await new Promise<void>((resolve, reject) => { await new Promise<void>((resolve, reject) => {
let retryCount = 0
srv.on('error', (err: NodeJS.ErrnoException) => {
// This code catches EADDRINUSE error if the port is already in use // This code catches EADDRINUSE error if the port is already in use
srv.on('error', reject) if (
err.code === 'EADDRINUSE' &&
serverOptions.allowRetry &&
port &&
retryCount < 10
) {
warn(`Port ${port} is in use, trying ${port + 1} instead.`)
port += 1
retryCount += 1
srv.listen(port, hostname)
} else {
reject(err)
}
})
srv.on('listening', () => resolve()) srv.on('listening', () => resolve())
srv.listen(port, hostname) srv.listen(port, hostname)
}) })
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment