I have websocket serwer created with this package https://websockets.readthedocs.io/en/stable/intro.html. I must stop restart this server at runtime.
My server runs as asyncio.Task but cancel() method seems to do nothing. Is there any way to stop this server task and after that start it again?
server.py
#!/usr/bin/env python3
import asyncio
import websockets
class App:
def __init__(self):
self._task = None
self._slots = []
async def worker(self, websocket, path):
data = await websocket.recv()
self._slots.append(data)
await websocket.send(f'prev: {"; ".join(self._slots)}')
self.stop_server()
def start_server(self):
self._task = asyncio.ensure_future(websockets.serve(self.worker, 'localhost', 5000))
def stop_server(self):
self._task.cancel() # this doeas not stop server :P
print(self._task.cancelled()) # always False
def run(self):
try:
loop = asyncio.get_event_loop()
self.start_server()
loop.run_forever()
finally:
loop.close()
App().run()
Test client
#!/usr/bin/env python
# WS client example
import asyncio
import websockets
async def hello():
async with websockets.connect(
'ws://localhost:5000') as websocket:
name = input("What's your name? ")
await websocket.send(name)
print(f"> {name}")
greeting = await websocket.recv()
print(f"< {greeting}")
asyncio.get_event_loop().run_until_complete(hello())