11""" 
22Telnet server. 
33""" 
4+ import  asyncio 
45import  contextvars  # Requires Python3.7! 
56import  socket 
6- from  asyncio  import  ensure_future ,  get_event_loop 
7+ from  asyncio  import  get_event_loop 
78from  typing  import  (
89 Awaitable ,
910 Callable ,
@@ -244,6 +245,7 @@ def __init__(self, host: str = '127.0.0.1', port: int = 23,
244245 self .interact  =  interact 
245246 self .encoding  =  encoding 
246247 self .style  =  style 
248+  self ._application_tasks : List [asyncio .Task ] =  []
247249
248250 self .connections : Set [TelnetConnection ] =  set ()
249251 self ._listen_socket : Optional [socket .socket ] =  None 
@@ -268,11 +270,18 @@ def start(self) -> None:
268270
269271 get_event_loop ().add_reader (self ._listen_socket , self ._accept )
270272
271-  def  stop (self ) ->  None :
273+  async   def  stop (self ) ->  None :
272274 if  self ._listen_socket :
273275 get_event_loop ().remove_reader (self ._listen_socket )
274276 self ._listen_socket .close ()
275277
278+  # Wait for all applications to finish. 
279+  for  t  in  self ._application_tasks :
280+  t .cancel ()
281+ 
282+  for  t  in  self ._application_tasks :
283+  await  t 
284+ 
276285 def  _accept (self ) ->  None :
277286 """ 
278287 Accept new incoming connection. 
@@ -297,6 +306,8 @@ async def run() -> None:
297306 print (e )
298307 finally :
299308 self .connections .remove (connection )
309+  self ._application_tasks .remove (task )
300310 logger .info ('Stopping interaction %r %r' , * addr )
301311
302-  ensure_future (run ())
312+  task  =  get_event_loop ().create_task (run ())
313+  self ._application_tasks .append (task )
0 commit comments