Skip to content

Commit

Permalink
Set socket blocking to false
Browse files Browse the repository at this point in the history
Handle EAGAIN & ECONNRESET
Fix sample file name.
  • Loading branch information
Karl Fleischmann committed Jul 20, 2022
1 parent 142c97d commit bcabd1d
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 16 deletions.
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
File renamed without changes.

0 comments on commit bcabd1d

Please sign in to comment.