关于python 3.x:无法停止aiohttp websocket服务器

Can't stop aiohttp websocket server

我无法从应用程序中取消我的aiohttp websocket服务器。当我收到"取消"字符串时,我想停止服务器并关闭
来自客户。是的,我明白了,我完成了我的协同例程(websocket_handler),但是aiohttp库中有三个协同例程仍在继续工作。

enter

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import aiohttp.web
from   aiohttp import ClientConnectionError, WSCloseCode

# This restores the default Ctrl+C signal handler, which just kills the process
#https://stackoverflow.com/questions/27480967/why-does-the-asyncios-event-loop-suppress-the-keyboardinterrupt-on-windows
import signal
signal.signal(signal.SIGINT, signal.SIG_DFL)

HOST = os.getenv('HOST', 'localhost')
PORT = int(os.getenv('PORT', 8881))

async def testhandle(request):
    #D?D?D??€D?D3?€D°D?D?D° D?D′?€D°D±D°????D2D°???‰D°?? http-D·D°D??€D??? D?D? D°D′?€Dμ????"http://127.0.0.1:8881/test"
    print("server: into testhandle()")
    return aiohttp.web.Response(text='Test handle')

async def websocket_handler(request):
    #D?D?D??€D?D3?€D°D?D?D° D?D′?€D°D±D°????D2D°???‰D°?? ws-D·D°D??€D??? D?D? D°D′?€Dμ????"http://127.0.0.1:8881"  
    print('Websocket connection starting')
    ws = aiohttp.web.WebSocketResponse()
    await ws.prepare(request)
    request.app['websockets'].add(ws)
    print('Websocket connection ready')
    try:
        async for msg in ws:
            if msg.type == aiohttp.WSMsgType.TEXT:
                if msg.data == 'close':
                    print(msg.data)
                    break    
                else:
                    print(msg.data)
                    await ws.send_str("You said: {}".format(msg.data))
            elif msg.type == aiohttp.WSMsgType.ERROR:
                print('ws connection closed with exception %s' %
                    ws.exception())            
    except (asyncio.CancelledError, ClientConnectionError):  
        pass    # D¢???? D?DoD°D·??D2D°DμD????? DoD?D3D′D°, DoD?D?DμD??? D???D2D°D?D?D?????.
                # D’ D±??D′???‰DμD? D?D?D?D?D? ?????? D???D2D?D±D?D?D′D°???? ?€Dμ?????€????.
    finally:
        print('Websocket connection closed')
        request.app['websockets'].discard(ws)
        #pending = asyncio.Task.all_tasks()
        #asyncio.get_event_loop().stop()
    return ws

async def on_shutdown(app):
    for ws in set(app['websockets']):
        await ws.close(code=WSCloseCode.GOING_AWAY, message='Server shutdown')  

def main():
    loop = asyncio.get_event_loop()
    app  = aiohttp.web.Application()
    app['websockets'] = weakref.WeakSet()
    app.on_shutdown.append(on_shutdown)  
    app.add_routes([aiohttp.web.get('/', websocket_handler)])        #, aiohttp.web.get('/test', testhandle)  

    try:
        aiohttp.web.run_app(app, host=HOST, port=PORT, handle_signals=True)
        print("after run_app")
    except Exception as exc:
        print ("in exception")
    finally:
        loop.close()

if __name__ == '__main__':
    main()


https://docs.aiohttp.org/zh/v3.0.1/web_reference.html#aiohttp.web.Application.shutdown

1
2
app.shutdown()
app.cleanup()

关闭后,您还应该执行cleanup()