@@ -327,26 +327,37 @@ def start(self, host: str, port: int = 80, root: str = "") -> None:
327
327
)
328
328
self ._sock .bind ((host , port ))
329
329
self ._sock .listen (10 )
330
+ self ._sock .setblocking (False ) # non-blocking socket
330
331
331
332
def poll (self ):
332
333
"""
333
334
Call this method inside your main event loop to get the server to
334
335
check for new incoming client requests. When a request comes in,
335
336
the application callable will be invoked.
336
337
"""
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
0 commit comments