gevent-socketio从线程发送消息 [英] gevent-socketio send message from thread

查看:270
本文介绍了gevent-socketio从线程发送消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



我试过这个:

  from flask import Flask,render_template $ b $ from flask.ext.socketio import SocketIO,send,emit 
import线程
导入时间
$ b $ app = Flask(__ name__)
app.config ['SECRET_KEY'] ='secret!'
socketio = SocketIO(app)
$ b $ socketio.on('message')
def handle_message(message):
send(message,broadcast = True)

@ app.route ')
def index():
return render_template('index.html')
$ b $ def ping_thread():
而真:
time.sleep(1)
print'Ping'
send('ping')

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

和它给我这个错误:

  RuntimeError:在请求上下文之外工作

如何从一个没有 @ socketio.on()装饰器的函数发送消息?我可以直接使用 gevent 发送消息给 socketio

解决方案

本部分的文档

a>:


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



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



不是从 from flask.ext.socketio导入SocketIO,发送 >,而是从 socketio = SocketIO(app)调用你的 socketio 变量。如果你完成了 socketio_connection = SocketIO(app),那么你会调用 socketio_connection.emit()数据。


I would like to use gevent-socketio to send messages from a worker thread and update all connected clients on the status of the job.

I tried this:

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)

And it gives me this error:

RuntimeError: working outside of request context

How do I send messages from a function that doesn't have the @socketio.on() decorator? Can I use gevent directly to send messages to socketio?

解决方案

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

This emit is not from from flask.ext.socketio import SocketIO, send, but instead called on your socketio variable from socketio = SocketIO(app). Had you done socketio_connection = SocketIO(app), then you'd be calling socketio_connection.emit() to broadcast your data.

这篇关于gevent-socketio从线程发送消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆