@@ -194,13 +194,23 @@ def serve_forever(
194194 except Exception : # pylint: disable=broad-except
195195 pass # Ignore exceptions in handler function
196196
197- def _set_socket_level_to_reuse_address (self ) -> None :
198- """
199- Only for CPython, prevents "Address already in use" error when restarting the server.
200- """
201- self ._sock .setsockopt (
202- self ._socket_source .SOL_SOCKET , self ._socket_source .SO_REUSEADDR , 1
203- )
197+ @staticmethod
198+ def _create_server_socket (
199+ socket_source : _ISocketPool ,
200+ host : str ,
201+ port : int ,
202+ ) -> _ISocket :
203+ sock = socket_source .socket (socket_source .AF_INET , socket_source .SOCK_STREAM )
204+
205+ # TODO: Temporary backwards compatibility, remove after CircuitPython 9.0.0 release
206+ if implementation .version >= (9 ,) or implementation .name != "circuitpython" :
207+ sock .setsockopt (socket_source .SOL_SOCKET , socket_source .SO_REUSEADDR , 1 )
208+
209+ sock .bind ((host , port ))
210+ sock .listen (10 )
211+ sock .setblocking (False ) # Non-blocking socket
212+
213+ return sock
204214
205215 def start (self , host : str , port : int = 80 ) -> None :
206216 """
@@ -215,16 +225,7 @@ def start(self, host: str, port: int = 80) -> None:
215225 self .host , self .port = host , port
216226
217227 self .stopped = False
218- self ._sock = self ._socket_source .socket (
219- self ._socket_source .AF_INET , self ._socket_source .SOCK_STREAM
220- )
221-
222- if implementation .name != "circuitpython" :
223- self ._set_socket_level_to_reuse_address ()
224-
225- self ._sock .bind ((host , port ))
226- self ._sock .listen (10 )
227- self ._sock .setblocking (False ) # Non-blocking socket
228+ self ._sock = self ._create_server_socket (self ._socket_source , host , port )
228229
229230 if self .debug :
230231 _debug_started_server (self )
0 commit comments