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,12 @@ 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+ # Only for CPython, prevents "Address already in use" error
200+ self ._sock .setsockopt (
201+ self ._socket_source .SOL_SOCKET , self ._socket_source .SO_REUSEADDR , 1
202+ )
203+
197204 def start (self , host : str , port : int = 80 ) -> None :
198205 """
199206 Start the HTTP server at the given host and port. Requires calling
@@ -210,15 +217,13 @@ def start(self, host: str, port: int = 80) -> None:
210217 self ._sock = self ._socket_source .socket (
211218 self ._socket_source .AF_INET , self ._socket_source .SOCK_STREAM
212219 )
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
220+
221+ if implementation .name != "circuitpython" :
222+ self ._set_socket_level_to_reuse_address ()
223+
224+ self ._sock .bind ((host , port ))
225+ self ._sock .listen (10 )
226+ self ._sock .setblocking (False ) # Non-blocking socket
222227
223228 if self .debug :
224229 _debug_started_server (self )
0 commit comments