2014-11-12 4 views
2

gevent-socketio를 사용하여 작업 스레드의 메시지를 보내고 연결된 모든 클라이언트를 작업 상태로 업데이트하고자합니다. 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) 

을 그리고 그것은 나에게이 오류 준다 : 나는 @socketio.on() 장식이없는 함수에서 메시지를 보낼 어떻게

RuntimeError: working outside of request context 

를? 에 직접 메시지를 보내려면 gevent을 사용할 수 있습니까? this section of the documentation에서

답변

2

:

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}) 

emitfrom flask.ext.socketio import SocketIO, send에서 아니지만, 대신 socketio = SocketIO(app)에서 socketio 변수라고합니다. socketio_connection = SocketIO(app)을 완료했다면 socketio_connection.emit()을 호출하여 데이터를 브로드 캐스트합니다.

+0

실제로 문서에서 해당 부분을 보지 못했습니다. 하지만 그건 정확히 내가 어쨌든 (내 코드를 참조하십시오)하려고 노력하고 그것은 나를 위해 작동하지 않습니다. –

+0

당신은'emit'을 호출하지만, 링크는'socketio.emit'을 호출합니다. – Celeo

+0

피드백에 감사드립니다, @Celeo. 내 코드를 더 많이 포함하도록 내 게시물을 업데이트했습니다. 보시다시피, 나는'socketio'가 아니라'emit'과'send'를 직접 가져오고 있습니다. 그래서 제 문제는 아닙니다. –

관련 문제