Skip to content

Fix for CPython "Adress already in use" error #79

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Feb 5, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 9 additions & 3 deletions adafruit_httpserver/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -210,9 +210,15 @@ 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
)
self._sock.bind((host, port))
self._sock.listen(10)
self._sock.setblocking(False) # Non-blocking socket
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 self.debug:
_debug_started_server(self)
Expand Down
3 changes: 2 additions & 1 deletion examples/httpserver_cpython.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,5 +19,6 @@ def base(request: Request):
return Response(request, "Hello from the CircuitPython HTTP Server!")


# runs on port 5000; ports < 1024 require sudo.
# Ports below 1024 are reserved for root user only.
# If you want to run this example on a port below 1024, you need to run it as root (or with `sudo`).
server.serve_forever("0.0.0.0", 5000)