[英]aiohttp Websocket client and HTTP server
I'm writing an application that needs to take in events from two sources. 我正在编写一个需要从两个来源获取事件的应用程序。 Some events will come from a Websocket client connection, and some will come from incoming HTTP requests.
一些事件将来自Websocket客户端连接,一些事件将来自传入的HTTP请求。 Is it possible with aiohttp to have both of these listeners in the same application, or do I need two separate executables?
使用aiohttp是否可以将两个侦听器都放在同一个应用程序中,还是我需要两个单独的可执行文件?
I currently have a function that takes websocket events, and calls a callback on each event 我目前有一个接受websocket事件并在每个事件上调用回调的函数
async def callback(msg):
print(msg)
async def websocket():
session = aiohttp.ClientSession()
async with session.ws_connect('http://example.org/websocket') as ws:
async for msg in ws:
if msg.type == aiohttp.WSMsgType.TEXT:
await callback(msg.data)
elif msg.type == aiohttp.WSMsgType.CLOSED:
break
elif msg.type == aiohttp.WSMsgType.ERROR:
break
The problem is that this blocks forever, so I don't know how I could integrate this with the aiohttp server. 问题是这将永远阻塞,因此我不知道如何将其与aiohttp服务器集成。 If I do:
如果我做:
await websocket()
aiohttp.web.run_app(app)
then web.run_app
is never called. 则永远不会调用
web.run_app
。 Is there some way to accomplish this? 有什么办法可以做到这一点? It seems like the ideal case for asyncio, multiple things handling multiple events asynchronously.
似乎是异步的理想情况,多个事物异步处理多个事件。 How do I do it?
我该怎么做?
I was able to accomplish my goals by using the on_startup
handler of my aiohttp app. 通过使用aiohttp应用程序的
on_startup
处理程序,我能够实现自己的目标。
async def callback(msg):
print(msg)
async def websocket(session):
async with session.ws_connect('http://example.org/websocket') as ws:
async for msg in ws:
if msg.type == aiohttp.WSMsgType.TEXT:
await callback(msg.data)
elif msg.type == aiohttp.WSMsgType.CLOSED:
break
elif msg.type == aiohttp.WSMsgType.ERROR:
break
async def init(app):
session = aiohttp.ClientSession()
app['websocket_task'] = app.loop.create_task(websocket(session))
app = web.Application()
app.on_startup.append(init)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.