python - 当从猴子修补的 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 的论坛上看到了一些关于这个的主题,它让我更接近了,但我仍然错过了一些东西......
解决方案
推荐阅读
- sapui5 - sap.m.Table 行为改变
- sql - 循环遍历特定ID的数字数组 - sql
- arrays - 如何获取每个团队的结果 laravel
- c# - 如何随机绘制 C# Windows 窗体应用程序?
- reactjs - 反应本机应用程序中缺少 .watchmanconfig 文件
- visual-studio - 使用 Visual Studio 2019 Pro 的 ExcludeFromCodeCoverageAttribute 从 OpenCover 代码覆盖率报告中排除类时遇到问题
- python - 带有多个参数的 Python 打印与打印 fstring
- aws-lambda - SQS lambda 缺少必需的参数缺少必需的键
- c# - 方法 Rotate 在 UWP 中无法正常工作
- android - 没有高于 Oreo (8.1) 的平台可用 Android SDK