Skip to content

Commit 1070165

Browse files
committed
Add timeout option to socket and make sure buffer has data
1 parent f9345f2 commit 1070165

File tree

1 file changed

+12
-3
lines changed

1 file changed

+12
-3
lines changed

adafruit_httpserver.py

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@
2424
except ImportError:
2525
pass
2626

27-
from errno import EAGAIN, ECONNRESET
27+
from errno import EAGAIN, ECONNRESET, ETIMEDOUT
2828
import os
2929

3030
__version__ = "0.0.0+auto.0"
@@ -333,17 +333,23 @@ def start(self, host: str, port: int = 80, root: str = "") -> None:
333333
self._sock.listen(10)
334334
self._sock.setblocking(False) # non-blocking socket
335335

336-
def poll(self):
336+
def poll(self, timeout=-1):
337337
"""
338338
Call this method inside your main event loop to get the server to
339339
check for new incoming client requests. When a request comes in,
340340
the application callable will be invoked.
341+
342+
:param int timeout: Optional timeout value in seconds.
341343
"""
342344
try:
343345
conn, _ = self._sock.accept()
344346
with conn:
345347
conn.setblocking(True)
348+
if timeout > 0:
349+
conn.settimeout(timeout)
346350
length, _ = conn.recvfrom_into(self._buffer)
351+
if length <= 0:
352+
return
347353

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

@@ -362,9 +368,12 @@ def poll(self):
362368
if ex.errno == EAGAIN:
363369
# there is no data available right now, try again later.
364370
return
365-
if ex.errno == ECONNRESET:
371+
elif ex.errno == ECONNRESET:
366372
# connection reset by peer, try again later.
367373
return
374+
elif ex.errno == ETIMEDOUT:
375+
# connection timed out
376+
return
368377
raise
369378

370379
@property

0 commit comments

Comments
 (0)