Skip to content
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

Allow Non-Blocking Socket Calls #10

Merged
merged 2 commits into from
Jul 22, 2022
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
43 changes: 27 additions & 16 deletions adafruit_httpserver.py
Original file line number Diff line number Diff line change
Expand Up @@ -327,26 +327,37 @@ def start(self, host: str, port: int = 80, root: str = "") -> None:
)
self._sock.bind((host, port))
self._sock.listen(10)
self._sock.setblocking(False) # non-blocking socket

def poll(self):
"""
Call this method inside your main event loop to get the server to
check for new incoming client requests. When a request comes in,
the application callable will be invoked.
"""
conn, _ = self._sock.accept()
with conn:
length, _ = conn.recvfrom_into(self._buffer)

request = _HTTPRequest(raw_request=self._buffer[:length])

# If a route exists for this request, call it. Otherwise try to serve a file.
route = self.routes.get(request, None)
if route:
response = route(request)
elif request.method == "GET":
response = HTTPResponse(filename=request.path, root=self.root_path)
else:
response = HTTPResponse(status=HTTPStatus.INTERNAL_SERVER_ERROR)

response.send(conn)
try:
conn, _ = self._sock.accept()
with conn:
length, _ = conn.recvfrom_into(self._buffer)

request = _HTTPRequest(raw_request=self._buffer[:length])

# If a route exists for this request, call it. Otherwise try to serve a file.
route = self.routes.get(request, None)
if route:
response = route(request)
elif request.method == "GET":
response = HTTPResponse(filename=request.path, root=self.root_path)
else:
response = HTTPResponse(status=HTTPStatus.INTERNAL_SERVER_ERROR)

response.send(conn)
except OSError as ex:
# handle EAGAIN and ECONNRESET
if ex.errno == EAGAIN:
# there is no data available right now, try again later.
return
if ex.errno == ECONNRESET:
# connection reset by peer, try again later.
return
raise