无法停止aiohttp websocket服务器

时间:2019-03-19 08:15:44

标签: python-3.x aiohttp

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

enter image description here

当然,我可以在我的例程结束时调用asyncio.get_event_loop().stop(),但是有停止停止aiohttp服务器的优美方法吗?

从我的代码中可以看到我尝试使用Application().on_shutdown.append(),但是失败了。

正确的方法是什么?

#!/ usr / bin / env python     #--编码:utf-8--     导入操作系统     导入异步     导入信号     导入weakref

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):
    #Сопрограмма одрабатывающая http-запрос по адресу "http://127.0.0.1:8881/test"
    print("server: into testhandle()")
    return aiohttp.web.Response(text='Test handle')

async def websocket_handler(request):
    #Сопрограмма одрабатывающая ws-запрос по адресу "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    # Тут оказываемся когда, клиент отвалился. 
                # В будущем можно тут освобождать ресурсы. 
    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()

1 个答案:

答案 0 :(得分:0)

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

app.shutdown()
app.cleanup()

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