Skip to content

Commit

Permalink
Merge pull request #80 from michalpokusa/cpython-fix-2
Browse files Browse the repository at this point in the history
Fix: AttributeError on CircuitPython
  • Loading branch information
FoamyGuy authored Feb 7, 2024
2 parents 4f31799 + 8b7d79e commit 1fb9ee8
Showing 1 changed file with 16 additions and 9 deletions.
25 changes: 16 additions & 9 deletions adafruit_httpserver/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
pass

from errno import EAGAIN, ECONNRESET, ETIMEDOUT
from sys import implementation
from time import monotonic, sleep
from traceback import print_exception

Expand Down Expand Up @@ -194,6 +195,14 @@ def serve_forever(
except Exception: # pylint: disable=broad-except
pass # Ignore exceptions in handler function

def _set_socket_level_to_reuse_address(self) -> None:
"""
Only for CPython, prevents "Address already in use" error when restarting the server.
"""
self._sock.setsockopt(
self._socket_source.SOL_SOCKET, self._socket_source.SO_REUSEADDR, 1
)

def start(self, host: str, port: int = 80) -> None:
"""
Start the HTTP server at the given host and port. Requires calling
Expand All @@ -210,15 +219,13 @@ def start(self, host: str, port: int = 80) -> None:
self._sock = self._socket_source.socket(
self._socket_source.AF_INET, self._socket_source.SOCK_STREAM
)
try:
# Only for CPython, prevents "Address already in use" error
self._sock.setsockopt(
self._socket_source.SOL_SOCKET, self._socket_source.SO_REUSEADDR, 1
)
finally:
self._sock.bind((host, port))
self._sock.listen(10)
self._sock.setblocking(False) # Non-blocking socket

if implementation.name != "circuitpython":
self._set_socket_level_to_reuse_address()

self._sock.bind((host, port))
self._sock.listen(10)
self._sock.setblocking(False) # Non-blocking socket

if self.debug:
_debug_started_server(self)
Expand Down

0 comments on commit 1fb9ee8

Please sign in to comment.