【问题标题】:gevent-socketio send message from threadgevent-socketio 从线程发送消息
【发布时间】:2015-01-09 18:28:27
【问题描述】:

我想使用 gevent-socketio 从工作线程发送消息并更新所有连接的客户端的作业状态。

我试过了:

from flask import Flask, render_template
from flask.ext.socketio import SocketIO, send, emit
import threading
import time

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

@socketio.on('message')
def handle_message(message):
    send(message, broadcast=True)

@app.route('/')
def index():
    return render_template('index.html')

def ping_thread():
    while True:
        time.sleep(1)
        print 'Pinging'
        send('ping')

if __name__ == '__main__':
    t = threading.Thread(target=ping_thread)
    t.daemon = True
    t.start()
    socketio.run(app)

它给了我这个错误:

RuntimeError: working outside of request context

如何从没有 @socketio.on() 装饰器的函数发送消息?可以直接用geventsocketio发消息吗?

【问题讨论】:

    标签: python flask socket.io gevent gevent-socketio


    【解决方案1】:

    来自this section of the documentation

    有时服务器需要成为消息的发起者。这对于向客户端发送源自服务器的事件的通知很有用。 socketio.send() 和 socketio.emit() 方法可用于向所有连接的客户端广播:

    def some_function():
        socketio.emit('some event', {'data': 42})
    

    这个emit 不是来自from flask.ext.socketio import SocketIO, send,而是从socketio = SocketIO(app) 调用你的socketio 变量。如果您完成了socketio_connection = SocketIO(app),那么您将调用socketio_connection.emit() 来广播您的数据。

    【讨论】:

    • 我实际上没有在文档中看到该部分(d'oh!)。但这正是我试图做的(见我上面的代码),它似乎对我不起作用。
    • 你打电话给emit,但链接说打电话给socketio.emit
    • 感谢@Celeo 的反馈。我已经更新了我的帖子以包含更多我的代码。如您所见,我是直接导入emitsend,而不是socketio,所以这不是我的问题。
    猜你喜欢
    • 2015-09-22
    • 2016-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-18
    • 2018-07-14
    • 2015-09-20
    相关资源
    最近更新 更多