reuse port without waiting to leave TIME-WAIT state (#1765)

* reuse port without waiting to leave TIME-WAIT state

* resuse port only when running gradio cli
This commit is contained in:
pngwn 2022-07-12 22:05:51 +01:00 committed by GitHub
parent a18c7ddf04
commit 8caec11d74
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 4 additions and 1 deletions

View File

@ -45,7 +45,7 @@ class Server(uvicorn.Server):
self.thread.join()
def get_first_available_port(initial: int, final: int) -> int:
def get_first_available_port(initial: int, final: int, reuse_port: bool = False) -> int:
"""
Gets the first open port in a specified range of port numbers
Parameters:
@ -57,6 +57,8 @@ def get_first_available_port(initial: int, final: int) -> int:
for port in range(initial, final):
try:
s = socket.socket() # create a socket object
if reuse_port:
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((LOCALHOST_NAME, port)) # Bind to the port
s.close()
return port

View File

@ -34,6 +34,7 @@ def run_in_reload_mode():
port = networking.get_first_available_port(
networking.INITIAL_PORT_VALUE,
networking.INITIAL_PORT_VALUE + networking.TRY_NUM_PORTS,
True,
)
print(
f"\nLaunching in *reload mode* on: http://{networking.LOCALHOST_NAME}:{port} (Press CTRL+C to quit)\n"