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,14 @@ 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
+ """
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
+
197
206
def start (self , host : str , port : int = 80 ) -> None :
198
207
"""
199
208
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:
210
219
self ._sock = self ._socket_source .socket (
211
220
self ._socket_source .AF_INET , self ._socket_source .SOCK_STREAM
212
221
)
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
222
229
223
230
if self .debug :
224
231
_debug_started_server (self )
0 commit comments