15
15
pass
16
16
17
17
from errno import EAGAIN , ECONNRESET , ETIMEDOUT
18
+ from sys import implementation
18
19
from time import monotonic , sleep
19
20
from traceback import print_exception
20
21
@@ -194,6 +195,12 @@ def serve_forever(
194
195
except Exception : # pylint: disable=broad-except
195
196
pass # Ignore exceptions in handler function
196
197
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
+
197
204
def start (self , host : str , port : int = 80 ) -> None :
198
205
"""
199
206
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:
210
217
self ._sock = self ._socket_source .socket (
211
218
self ._socket_source .AF_INET , self ._socket_source .SOCK_STREAM
212
219
)
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
222
227
223
228
if self .debug :
224
229
_debug_started_server (self )
0 commit comments