1515 pass
1616
1717from errno import EAGAIN , ECONNRESET , ETIMEDOUT
18+ from sys import implementation
1819from time import monotonic , sleep
1920from traceback import print_exception
2021
@@ -194,6 +195,14 @@ def serve_forever(
194195 except Exception : # pylint: disable=broad-except
195196 pass # Ignore exceptions in handler function
196197
198+ def _set_socket_level_to_reuse_address (self ) -> None :
199+ """
200+ Only for CPython, prevents "Address already in use" error when restarting the server.
201+ """
202+ self ._sock .setsockopt (
203+ self ._socket_source .SOL_SOCKET , self ._socket_source .SO_REUSEADDR , 1
204+ )
205+
197206 def start (self , host : str , port : int = 80 ) -> None :
198207 """
199208 Start the HTTP server at the given host and port. Requires calling
@@ -210,15 +219,13 @@ def start(self, host: str, port: int = 80) -> None:
210219 self ._sock = self ._socket_source .socket (
211220 self ._socket_source .AF_INET , self ._socket_source .SOCK_STREAM
212221 )
213- try :
214- # Only for CPython, prevents "Address already in use" error
215- self ._sock .setsockopt (
216- self ._socket_source .SOL_SOCKET , self ._socket_source .SO_REUSEADDR , 1
217- )
218- finally :
219- self ._sock .bind ((host , port ))
220- self ._sock .listen (10 )
221- self ._sock .setblocking (False ) # Non-blocking socket
222+
223+ if implementation .name != "circuitpython" :
224+ self ._set_socket_level_to_reuse_address ()
225+
226+ self ._sock .bind ((host , port ))
227+ self ._sock .listen (10 )
228+ self ._sock .setblocking (False ) # Non-blocking socket
222229
223230 if self .debug :
224231 _debug_started_server (self )
0 commit comments