Bridging websocket requests to ZMQ and back

1k Views Asked by At

I created a web socket server with ws4py that dispatches messages to a ZMQ message bus and returns responses to the web socket. The stripped down code looks like this:

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

In this minimal example, I removed the processing part of the system that sends results back to the message bus and subscribe to message directly (essentially making it a complicated echo server). The problem is that _recv_result() is never being called. I removed all subscription filter prefixes, and made it a gevent thread, but this doesn't help. Does anyone have an idea what might be wrong?

0

There are 0 best solutions below