Skip to content

Commit b218af3

Browse files
authored
Merge pull request #10 from karlfl/NonBlockingSocket
Allow Non-Blocking Socket Calls
2 parents 142c97d + d021005 commit b218af3

File tree

2 files changed

+27
-16
lines changed

2 files changed

+27
-16
lines changed

Diff for: adafruit_httpserver.py

+27-16
Original file line numberDiff line numberDiff line change
@@ -327,26 +327,37 @@ def start(self, host: str, port: int = 80, root: str = "") -> None:
327327
)
328328
self._sock.bind((host, port))
329329
self._sock.listen(10)
330+
self._sock.setblocking(False) # non-blocking socket
330331

331332
def poll(self):
332333
"""
333334
Call this method inside your main event loop to get the server to
334335
check for new incoming client requests. When a request comes in,
335336
the application callable will be invoked.
336337
"""
337-
conn, _ = self._sock.accept()
338-
with conn:
339-
length, _ = conn.recvfrom_into(self._buffer)
340-
341-
request = _HTTPRequest(raw_request=self._buffer[:length])
342-
343-
# If a route exists for this request, call it. Otherwise try to serve a file.
344-
route = self.routes.get(request, None)
345-
if route:
346-
response = route(request)
347-
elif request.method == "GET":
348-
response = HTTPResponse(filename=request.path, root=self.root_path)
349-
else:
350-
response = HTTPResponse(status=HTTPStatus.INTERNAL_SERVER_ERROR)
351-
352-
response.send(conn)
338+
try:
339+
conn, _ = self._sock.accept()
340+
with conn:
341+
length, _ = conn.recvfrom_into(self._buffer)
342+
343+
request = _HTTPRequest(raw_request=self._buffer[:length])
344+
345+
# If a route exists for this request, call it. Otherwise try to serve a file.
346+
route = self.routes.get(request, None)
347+
if route:
348+
response = route(request)
349+
elif request.method == "GET":
350+
response = HTTPResponse(filename=request.path, root=self.root_path)
351+
else:
352+
response = HTTPResponse(status=HTTPStatus.INTERNAL_SERVER_ERROR)
353+
354+
response.send(conn)
355+
except OSError as ex:
356+
# handle EAGAIN and ECONNRESET
357+
if ex.errno == EAGAIN:
358+
# there is no data available right now, try again later.
359+
return
360+
if ex.errno == ECONNRESET:
361+
# connection reset by peer, try again later.
362+
return
363+
raise
File renamed without changes.

0 commit comments

Comments
 (0)