停止websockets.serve创建的websocket服务器

濮君植
2023-12-01

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()

测试客户端

#!/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())
 类似资料: