如何将异步套接字 io 与 aiohttp 混合使用

How to mix async socket io with aiohttp

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

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

在 http 请求上,我向 socket io 客户端发送消息并等待来自 socket io 的响应消息。然后将此消息作为 http 响应或超时发送。这里是"getting started"代码,我想采用

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)

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

你可以使用 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 对象。否则客户端可能会收到在不同会话中请求的数据。