flask-sockets 和 ZeroMQ
flask-sockets and ZeroMQ
我正在尝试使用 websocket 将 zeromq
pub/sub 消息发送到浏览器。以下 "works",消息确实通过 websocket 发送。但是,尝试重新加载页面只是挂起,因为我猜 while True
循环正在阻塞。我认为 gevent.sleep()
调用将允许上下文切换,但显然不是。知道如何让所有这些部分一起工作吗?
import zmq
import json
import gevent
from flask_sockets import Sockets
from flask import Flask, render_template
import logging
from gevent import monkey
monkey.patch_all()
app = Flask(__name__)
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
sockets = Sockets(app)
context = zmq.Context()
ZMQ_LISTENING_PORT = 6557
@app.route('/')
def index():
return render_template('index.html')
@sockets.route('/zeromq')
def send_data(ws):
logger.info('Got a websocket connection, sending up data from zmq')
socket = context.socket(zmq.SUB)
socket.connect('tcp://localhost:{PORT}'.format(PORT=ZMQ_LISTENING_PORT))
socket.setsockopt(zmq.SUBSCRIBE, "")
gevent.sleep()
while True:
data = socket.recv_json()
logger.info(data)
ws.send(json.dumps(data))
gevent.sleep()
if __name__ == '__main__':
from gevent import pywsgi
from geventwebsocket.handler import WebSocketHandler
server = pywsgi.WSGIServer(('', 25000), app, handler_class=WebSocketHandler)
server.serve_forever()
没关系,刚意识到需要做
import zmq.green as zmq
为了与 gevent 兼容使用。 Here's a link to pyZeormq docs.
我正在尝试使用 websocket 将 zeromq
pub/sub 消息发送到浏览器。以下 "works",消息确实通过 websocket 发送。但是,尝试重新加载页面只是挂起,因为我猜 while True
循环正在阻塞。我认为 gevent.sleep()
调用将允许上下文切换,但显然不是。知道如何让所有这些部分一起工作吗?
import zmq
import json
import gevent
from flask_sockets import Sockets
from flask import Flask, render_template
import logging
from gevent import monkey
monkey.patch_all()
app = Flask(__name__)
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
sockets = Sockets(app)
context = zmq.Context()
ZMQ_LISTENING_PORT = 6557
@app.route('/')
def index():
return render_template('index.html')
@sockets.route('/zeromq')
def send_data(ws):
logger.info('Got a websocket connection, sending up data from zmq')
socket = context.socket(zmq.SUB)
socket.connect('tcp://localhost:{PORT}'.format(PORT=ZMQ_LISTENING_PORT))
socket.setsockopt(zmq.SUBSCRIBE, "")
gevent.sleep()
while True:
data = socket.recv_json()
logger.info(data)
ws.send(json.dumps(data))
gevent.sleep()
if __name__ == '__main__':
from gevent import pywsgi
from geventwebsocket.handler import WebSocketHandler
server = pywsgi.WSGIServer(('', 25000), app, handler_class=WebSocketHandler)
server.serve_forever()
没关系,刚意识到需要做
import zmq.green as zmq
为了与 gevent 兼容使用。 Here's a link to pyZeormq docs.