我创建了一个带有ws4py
的Web套接字服务器,它将消息分派给ZMQ消息总线并将响应返回给Web套接字。精简代码如下所示:
from multiprocessing import Process
from gevent import monkey; monkey.patch_all()
from ws4py.websocket import WebSocket
from ws4py.server.geventserver import WSGIServer
from ws4py.server.wsgiutils import WebSocketWSGIApplication
import time
import gevent
from zmq.green.eventloop import ioloop, zmqstream
import zmq.green as zmq
class MyWebSocket(WebSocket):
def __init__(self, *args, **kwargs):
super(MyWebSocket, self).__init__(*args, **kwargs)
uri = 'tcp://127.0.0.1:5560'
context = zmq.Context()
self.publisher = context.socket(zmq.PUB)
self.publisher.bind(uri)
subscriber = context.socket(zmq.SUB)
subscriber.connect(uri)
subscriber.setsockopt(zmq.SUBSCRIBE, '')
loop = ioloop.IOLoop()
zstream = zmqstream.ZMQStream(subscriber, loop)
def _recv_result(msg):
print 'received from publisher', msg
zstream.on_recv(_recv_result)
gevent.spawn(loop.start)
def received_message(self, message):
# incoming from web client.
data = message.data
self.publisher.send_multipart(['id', data])
if __name__ == '__main__':
host, port = 'localhost', 9000
server = WSGIServer(
(host, port), WebSocketWSGIApplication(handler_cls=MyWebSocket)
)
server.serve_forever()
在这个最小的例子中,我删除了系统的处理部分,它将结果发送回消息总线并直接订阅消息(实际上使它成为一个复杂的echo服务器)。问题是永远不会调用_recv_result()
。我删除了所有订阅过滤器前缀,并使其成为gevent
线程,但这没有帮助。有没有人知道可能出现什么问题?