def onConnect(self, request): global pub_sock if pub_sock is not None: zf = ZmqFactory() e = ZmqEndpoint(ZmqEndpointType.connect, pub_sock) s = ZmqSubConnection(zf, e) s.gotMessage = lambda payload, topic: self.gotMessage( payload, topic) self._zmq = s self._guards = {} self._filters = [] # By default, subscribe messages from the current path and below default_filter = get_physical_path_from_vhm_path( self._environ["PATH_INFO"]) logger.debug("SUBSCRIBE " + default_filter) self._zmq.subscribe(default_filter.encode('utf-8')) self._filters.append(default_filter) # Cleanup inherited environ self._environ["HTTP_CONNECTION"] = "keep-alive" for env in [ "HTTP_UPGRADE", "HTTP_SEC_WEBSOCKET_EXTENSIONS", "HTTP_SEC_WEBSOCKET_KEY", "HTTP_SEC_WEBSOCKET_VERSION", "wsgi.errors", "wsgi.input", ]: if env in self._environ: del self._environ[env]
def setup_zmq(self): zmq_factory = ZmqFactory() print("subscribing on: %s" % self.endpoint) sub_endpoint = ZmqEndpoint(ZmqEndpointType.connect, self.endpoint) sub_connection = ZmqSubConnection(zmq_factory, sub_endpoint) sub_connection.gotMessage = self.zmq_message sub_connection.subscribe(INVOICE_PAYMENT_TAG)
def setup_zmq(self): zmq_factory = ZmqFactory() print("subscribing on: %s" % self.endpoint) sub_endpoint = ZmqEndpoint(ZmqEndpointType.connect, self.endpoint) sub_connection = ZmqSubConnection(zmq_factory, sub_endpoint) sub_connection.gotMessage = self.zmq_message sub_connection.subscribe(FORWARD_EVENT_TAG) sub_connection.subscribe(HTLC_ACCEPTED_TAG) print("subscribing on: %s" % self.mock_endpoint) sub_mock_endpoint = ZmqEndpoint(ZmqEndpointType.connect, self.mock_endpoint) sub_mock_connection = ZmqSubConnection(zmq_factory, sub_mock_endpoint) sub_mock_connection.gotMessage = self.zmq_message sub_mock_connection.subscribe(FORWARD_EVENT_TAG) sub_mock_connection.subscribe(HTLC_ACCEPTED_TAG)
def __init__(self): self.queue = Queue() self.zmq_factory = ZmqFactory() endpoint = ZmqEndpoint(ZmqEndpointType.connect, ZMQ_ENDPOINT) connection = ZmqSubConnection(self.zmq_factory, endpoint) connection.gotMessage = self.set_mode connection.subscribe(ZMQ_TAG)
def _load_setup(self, setup): for e, notification_type_names in setup.items(): endpoint = ZmqEndpoint(ZmqEndpointType.connect, e) connection = ZmqSubConnection(self.factory, endpoint) for n in notification_type_names: tag = n.encode("utf8") connection.gotMessage = self._log_message connection.subscribe(tag)
def __init__(self, endpoint, callBack=None): try: if endpoint: logger.debug("开始运行 SUB 客户端 , 连接的服务器地址为:{}...".format(endpoint)) self._sub = ZmqSubConnection(ZmqFactory(), ZmqEndpoint("connect", endpoint)) if callBack: self.setCallback(callBack) else: self.setCallback(self.doDataReceived) except Exception as e: logger.error(e)
def __init__(self, zmq_port): server_port = str(8001) self.resource = ImageResource() self.site = server.Site(self.resource) self.zmqFactory = ZmqFactory() self.zmqEndpoint = ZmqEndpoint('connect', 'tcp://127.0.0.1:' + zmq_port) self.zmqSubscriber = ZmqSubConnection(self.zmqFactory, self.zmqEndpoint) self.zmqSubscriber.subscribe("") self.zmqSubscriber.gotMessage = self.resource.imageReceived self.resourceEndpoint = reactor.listenTCP(int(server_port), self.site)
def startService(self): self._factory = ZmqFactory() endpoints = [ ZmqEndpoint(ZmqEndpointType.connect, endpoint) for endpoint in self.endpoints ] log.msg("Configuring ZeroMQ subscription socket", logLevel=logging.DEBUG) for endpoint in endpoints: log.msg("Connecting to the {endpoint} ZeroMQ endpoint".format( endpoint=endpoint)) s = ZmqSubConnection(self._factory, endpoint) s.subscribe(b"") s.gotMessage = self.on_message log.msg("ZeroMQ consumer is ready")
def __init__(self, reactor, screen_ui, audio_player, first_block_hash): f = ZmqFactory() f.reactor = reactor e = ZmqEndpoint("connect", "tcp://127.0.0.1:28332") s = ZmqSubConnection(f, e) s.subscribe("hashblock".encode("utf-8")) s.messageReceived = self.listener self.screen_ui = screen_ui self.new_block_queue = [] self.queue_running = False self.audio_player = audio_player new_block = NewBlock(self, first_block_hash, self.screen_ui, audio_player) self.new_block_queue.append(new_block) self._try_next()
def onClientMessage(self, payload, binary=False): if binary: message = self._errorTemplate % (-1, 'Expected text got binary data') self.sendMessage(message) elif self.uuid: # Already initialized return elif not self.isUuid(payload): message = self._errorTemplate % (1, 'Invalid client uuid') self.sendMessage(message) else: # Initialize ZMQ self.uuid = payload self.zmq = ZmqSubConnection(_zmqFactory, self.zmqEndpoint) self.zmq.gotMessage = self.onZmqMessage self.updateSubscriptionsAsync() self.sendMessage('{"status": "ok"}') msg = self.getMessages() for m in msg: self.sendMessage(json.dumps({'message': m}))
def __init__(self, gdata): self.gdata = gdata self.config = gdata.config self.que = deque() self.cache = gdata.cache self.db_engine = gdata.db_engine self.metadata = models.get_metadata(self.db_engine) self.ops = { 'radstart':self.start_session, 'radstop':self.stop_session } self.radstart = ZmqPullConnection(ZmqFactory(), ZmqEndpoint('connect', self.config.mqproxy.radstart_connect)) self.radstop = ZmqSubConnection(ZmqFactory(), ZmqEndpoint('connect',self.config.mqproxy.radstop_connect)) self.radresp = ZmqPushConnection(ZmqFactory(), ZmqEndpoint('connect', self.config.mqproxy.radresp_connect)) self.radstop.subscribe('radstop') self.radstop.gotMessage = self.subdataReceived self.radstart.onPull = self.dataReceived self.process_poll() logger.info("Start radstart %s" % self.radstart) logger.info("Start radstop %s" % self.radstop) logger.info("Start radresp %s" % self.radresp)
def main(): parser = OptionParser("") parser.add_option("-m", "--method", dest="method", help="0MQ socket connection: bind|connect") parser.add_option("-e", "--endpoint", dest="endpoint", help="0MQ Endpoint") parser.set_defaults(method="connect", endpoint="tcp://localhost:5555") (options, args) = parser.parse_args() zf = ZmqFactory() e = ZmqEndpoint(options.method, options.endpoint) s = ZmqSubConnection(zf, e) s.subscribe("") def doPrint(*args): print "message received: %r" % (args, ) s.gotMessage = doPrint reactor.run()
def sockjs_server(**options): configure = options.get('configure', False) port = options.get('port', 8888) sockjs_options = { 'websocket': True, 'cookie_needed': False, 'heartbeat': 25, 'timeout': 5, 'streaming_limit': 128 * 1024, 'encoding': 'cp1252', # Latin1 'sockjs_url': 'https://d1fxtkz8shb9d2.cloudfront.net/sockjs-0.3.js' } zf = ZmqFactory() endpoint = '%s://localhost:%d' % (settings.FORWARDER_PUB_TRANSPORT, settings.FORWARDER_PUB_PORT) e = ZmqEndpoint("connect", endpoint) subscription = ZmqSubConnection(zf, e) # Subscripción a todos los mensajes subscription.subscribe("") class SockJSProtocol(protocol.Protocol): DIRECT_FORWARD_MESSAGE_TYPES = ('echo', ) instances = [] def __init__(self, *largs, **kwargs): print "SockJS" #protocol.Protocol.__init__(*largs, **kwargs) SockJSProtocol.instances.append(self) def dataReceived(self, data_string): try: data = json.loads(data_string) msgtype = data.get('type', None) if msgtype in self.DIRECT_FORWARD_MESSAGE_TYPES: self.send_json(data, timestamp=repr(datetime.now())) except ValueError as e: print e self.send_json({'data': data_string, 'type': 'unknown'}) def send_json(self, data=None, **opts): '''Envia una respuesta en JSON por el websocket''' if data: if isinstance(data, dict): data_safe = copy(data) data_safe.update(opts) elif isinstance(data, basestring): try: data_safe = json.loads(data) except ValueError: raise ValueError("Can't convert %s to json" % data) else: data_safe = opts self.transport.write(json.dumps(data_safe)) def connectionLost(self, reason): print "Cerrando Socket" self.instances.remove(self) protocol.Protocol.connectionLost(self, reason) @classmethod def broadcast(cls, data, *largs, **kwargs): print "Received from forwarder %s" % data for conn in cls.instances: try: conn.send_json(data) except Exception as e: print e subscription.gotMessage = SockJSProtocol.broadcast factory = protocol.ServerFactory() factory.protocol = SockJSProtocol reactor.listenTCP(port, SockJSFactory(factory, sockjs_options)) print "SocketServer running on %d" % port if not configure: try: reactor.run() except error.ReactorNotRunning: print "Closing bridge"
def connect_subscriber(address): socket = ZmqSubConnection(ZmqFactory(), ZmqEndpoint("connect", address)) return socket
dest="mode", help="Mode: publisher|subscriber") parser.set_defaults(method="connect", endpoint="epgm://eth1;239.0.5.3:10011") (options, args) = parser.parse_args() zf = ZmqFactory() e = ZmqEndpoint(options.method, options.endpoint) if options.mode == "publisher": s = ZmqPubConnection(zf, e) def publish(): data = str(time.time()) print "publishing %r" % data s.publish(data) reactor.callLater(1, publish) publish() else: s = ZmqSubConnection(zf, e) s.subscribe("") def doPrint(*args): print "message received: %r" % (args, ) s.gotMessage = doPrint reactor.run()
from rpi.config import ZMQ_PORT, local_configs ## publisher _context = zmq.Context() _pub_socket = _context.socket(zmq.PUB) _pub_socket.bind("tcp://*:{}".format(ZMQ_PORT)) def zmq_publish(msg): print('publishing "{}" to peers via 0mq'.format(msg)) _pub_socket.send(msg) ###### subscriber, for twisted ###### zf = ZmqFactory() subscriber = ZmqSubConnection(zf) def _create_endpoint(treename): return ZmqEndpoint( "connect", "tcp://{}:{}".format(local_configs['other_trees'][treename], ZMQ_PORT)) _endpoints = [ _create_endpoint(treename) for treename in local_configs['connect_to'] ] subscriber.addEndpoints(_endpoints) # in `main.py`, specific behavior is configured, such as:
def add_sub(self, endpoint): if endpoint: logger.debug("开始运行 SUB 客户端 , 连接的服务器地址为:{}...".format(endpoint)) self.sub_ = ZmqSubConnection(ZmqFactory(), ZmqEndpoint("connect", endpoint)) self.set_callback()