首页 > 解决方案 > 在 python 中同时运行 Asyncio 和 Socketio

问题描述

我想在我的程序中运行两个 websocket,其中一个与我的 Raspberry Pi(通过 websockets)通信,另一个通过 Flask-SocketIO 与我的浏览器通信。当我在两个不同的 python 文件中运行它们时,一切都运行良好。但我不能让它们在同一个文件中运行。这是 Flask-SocketIO 服务器:

from flask import Flask, render_template
from flask_socketio import SocketIO

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app)

@app.route('/hello')
def hello():
    return 'Hello'

def main():
    print("abc")

if __name__ == '__main__':
    socketio.run(app, debug=True, port=5000)
    print("defg")

输出:

 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: ...
(12444) wsgi starting up on http://...

注意被打印出来。

这是 websockets 服务器:(您可以在移动房屋 github 上搜索 OCPP Python 时找到那段代码)

import asyncio
import logging
import websockets
from datetime import datetime

from ocpp.routing import on
from ocpp.v201 import ChargePoint as cp
from ocpp.v201 import call_result

logging.basicConfig(level=logging.INFO)


class ChargePoint(cp):    
# One function was left out to decluster the question

async def on_connect(websocket, path):
    try:
        requested_protocols = websocket.request_headers[
            'Sec-WebSocket-Protocol']
    except KeyError:
        logging.info("Client hasn't requested any Subprotocol. "
                 "Closing Connection")
    if websocket.subprotocol:
        logging.info("Protocols Matched: %s", websocket.subprotocol)
    else:
        # In the websockets lib if no subprotocols are supported by the
        # client and the server, it proceeds without a subprotocol,
        # so we have to manually close the connection.
        logging.warning('Protocols Mismatched | Expected Subprotocols: %s,'
                        ' but client supports  %s | Closing connection',
                        websocket.available_subprotocols,
                        requested_protocols)
        return await websocket.close()

    charge_point_id = path.strip('/')
    cp = ChargePoint(charge_point_id, websocket)

    await cp.start()


async def main():
    server = await websockets.serve(
        on_connect,
        '0.0.0.0',
        9000,
        subprotocols=['ocpp2.0.1']
    )
    logging.info("WebSocket Server Started")
    print("456")
    await server.wait_closed()

if __name__ == '__main__':
    asyncio.run(main())
    print("123")

输出

INFO:root:WebSocket Server Started
456

我尝试将它们全部粘贴到同一个文档中,然后这样做:

if __name__ == '__main__':
    asyncio.run(main())
    print("123")
    socketio.run(app, debug=True, port=5000)
    print("456")

但这只是运行第一个 asyncio.run(main()) 并且不打印 123 等。如果我切换它,它也只会运行第一个 .run 而不是停止。

我尝试了线程,但结果相同。有谁知道我如何同时运行这两个?

标签: pythonpython-asyncioflask-socketio

解决方案


推荐阅读