简体   繁体   English

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

[英]How to mix async socket io with aiohttp

I want to write http server with socket io. 我想用套接字io写http服务器。 What I need: 我需要的:

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

On http request, I send message to socket io client and wait response message from socket io. 在http请求时,我向套接字io客户端发送消息,并等待来自套接字io的响应消息。 Then send this message as http response or timeout. 然后将此消息作为http响应或超时发送。 Here "getting started" code, which I want to adopt. 这里要采用的“入门”代码。

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)

I dont understund how to link http part with socket io 我不了解如何将HTTP部分与套接字io链接

You could use asyncio.Queue for that: 您可以asyncio.Queue使用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)

Note: 注意:

to handle multiple concurrent sessions you should create a separate asyncio.Queue object for each session. 要处理多个并发会话,您应该为每个会话创建一个单独的asyncio.Queue对象。 Otherwise clients could receive the data which was requested in a different session. 否则,客户端可能会收到在另一个会话中请求的数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM