Skip to main content
 首页 » 编程设计

python之gevent-socketio 从线程发送消息

2024年10月25日12dyllove98

我想使用 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() 装饰器的函数发送消息?我可以直接使用gevent向socketio发送消息吗?

请您参考如下方法:

来自 this section of the documentation :

Sometimes the server needs to be the originator of a message. This can be useful to send a notification to clients of an event that originated in the server. The socketio.send() and socketio.emit() methods can be used to broadcast to all connected clients:

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

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