1

我正在zeromq尝试使用 websocket 将发布/订阅消息发送到浏览器。以下“有效”,因为消息确实通过 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()
4

1 回答 1

3

没关系,只是意识到需要做

import zmq.green as zmq

为了与 gevent 兼容使用。这是 pyZeormq 文档的链接。

于 2016-09-30T19:34:34.700 回答