【问题标题】:How to mix async socket io with aiohttp如何将异步套接字 io 与 aiohttp 混合使用
【发布时间】:2023-03-11 11:15:01
【问题描述】:

我想用socket io写http服务器。我需要什么:

request --> socket io ask -> socket io answer -> response

根据 http 请求,我向套接字 io 客户端发送消息并等待来自套接字 io 的响应消息。然后将此消息作为 http 响应或超时发送。这里是“入门”代码,我想采用。

from aiohttp import web
import socketio

sio = socketio.AsyncServer()
app = web.Application()
sio.attach(app)

async def index(request):
    sio.emit('ask', 'some data')
    # here I want wait socket io answer
    return web.Response(..., content_type='text/plain')

@sio.on('connect', namespace='/chat')
def connect(sid, environ):
    print("connect ", sid)

@sio.on('answer', namespace='/chat')
async def answer(sid, data):
    # here I want send response to index or timeout
    ...

@sio.on('disconnect', namespace='/chat')
def disconnect(sid):
    print('disconnect ', sid)

app.router.add_get('/', index)

if __name__ == '__main__':
    web.run_app(app)

我不明白如何将 http 部分与套接字 io 链接

【问题讨论】:

    标签: python python-asyncio coroutine aiohttp


    【解决方案1】:

    您可以为此使用asyncio.Queue

    from aiohttp import web
    import socketio
    import asyncio
    
    queue = asyncio.Queue()  # create queue object
    sio = socketio.AsyncServer()
    app = web.Application()
    sio.attach(app)
    
    async def index(request):
        sio.emit('ask', 'some data')
        response = await queue.get()  # block until there is something in the queue
        return web.Response(response, content_type='text/plain')
    
    @sio.on('connect', namespace='/chat')
    def connect(sid, environ):
        print("connect ", sid)
    
    @sio.on('answer', namespace='/chat')
    async def answer(sid, data):
        await queue.put(data)  # push the response data to the queue
    
    @sio.on('disconnect', namespace='/chat')
    def disconnect(sid):
        print('disconnect ', sid)
    
    app.router.add_get('/', index)
    
    if __name__ == '__main__':
        web.run_app(app)
    

    注意:

    要处理多个并发会话,您应该为每个会话创建一个单独的asyncio.Queue 对象。否则客户端可能会收到在不同会话中请求的数据。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-04-09
      • 1970-01-01
      • 1970-01-01
      • 2017-03-04
      • 1970-01-01
      • 1970-01-01
      • 2022-08-03
      相关资源
      最近更新 更多