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

时间:2019-04-15 16:37:59

标签: python python-asyncio coroutine aiohttp

我想用套接字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链接

1 个答案:

答案 0 :(得分:0)

您可以使用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对象。否则,客户端可能会收到其他会话中请求的数据。