Skip to content

Commit 60b4417

Browse files
committed
uasyncio: close server socket on server termination
This is needed to support cancelling the server task
1 parent 110c57c commit 60b4417

File tree

1 file changed

+19
-16
lines changed

1 file changed

+19
-16
lines changed

uasyncio/uasyncio/__init__.py

Lines changed: 19 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -235,23 +235,26 @@ def start_server(client_coro, host, port, backlog=10):
235235
ai = _socket.getaddrinfo(host, port, 0, _socket.SOCK_STREAM)
236236
ai = ai[0]
237237
s = _socket.socket(ai[0], ai[1], ai[2])
238-
s.setblocking(False)
238+
try:
239+
s.setblocking(False)
239240

240-
s.setsockopt(_socket.SOL_SOCKET, _socket.SO_REUSEADDR, 1)
241-
s.bind(ai[-1])
242-
s.listen(backlog)
243-
while True:
244-
if DEBUG and __debug__:
245-
log.debug("start_server: Before accept")
246-
yield IORead(s)
247-
if DEBUG and __debug__:
248-
log.debug("start_server: After iowait")
249-
s2, client_addr = s.accept()
250-
s2.setblocking(False)
251-
if DEBUG and __debug__:
252-
log.debug("start_server: After accept: %s", s2)
253-
extra = {"peername": client_addr}
254-
yield client_coro(StreamReader(s2), StreamWriter(s2, extra))
241+
s.setsockopt(_socket.SOL_SOCKET, _socket.SO_REUSEADDR, 1)
242+
s.bind(ai[-1])
243+
s.listen(backlog)
244+
while True:
245+
if DEBUG and __debug__:
246+
log.debug("start_server: Before accept")
247+
yield IORead(s)
248+
if DEBUG and __debug__:
249+
log.debug("start_server: After iowait")
250+
s2, client_addr = s.accept()
251+
s2.setblocking(False)
252+
if DEBUG and __debug__:
253+
log.debug("start_server: After accept: %s", s2)
254+
extra = {"peername": client_addr}
255+
yield client_coro(StreamReader(s2), StreamWriter(s2, extra))
256+
finally:
257+
s.close()
255258

256259

257260
import uasyncio.core

0 commit comments

Comments
 (0)