首页 > 解决方案 > 当从猴子修补的 gevent 线程调用时,socketio.emit() 没有发送给用户

问题描述

我有可以使用 向连接的用户发送消息的代码socketio.emit(),但是当从 gevent 线程执行相同的操作时,数据永远不会到达客户端。

示例代码:

from flask import Flask, request, render_template
from flask_socketio import SocketIO, join_room, leave_room, emit
import gevent
from gevent import monkey
monkey.patch_all()

app = Flask(__name__)
app.config['SECRET_KEY'] = '<redacted>'
app.debug = False
socket = SocketIO(app, async_mode="gevent")

def sendStamina(sessionId, stamina):
    # have to use socket.emit here, simply because this function is called from an BG thread.
    with app.test_request_context('/'):
        socket.emit('stamina', {'sessiondId': sessionId, 'stamina': stamina}, room=sessionId)
        print("sent satmina update")

def stamina_update():
    print("stamina update called")
    next_call = time.time()
    while 1:
        print("stamina update called inside")
        next_call = next_call + 1
        gevent.sleep(next_call - time.time())
        sendStamina(<data>, <data>)


t1 = gevent.spawn(game.stamina_update)
t2 = gevent.spawn(start_server)
gevent.joinall([t1, t2])

我在 SO 和 socketio 的论坛上看到了一些关于这个的主题,它让我更接近了,但我仍然错过了一些东西......

标签: pythonflask-socketio

解决方案


推荐阅读