async def main(): ctx = zmq.asyncio.Context() sock = ctx.socket(zmq.ROUTER) sock.bind('tcp://{}:{}'.format('*', 5672)) print('Connected to socket.') message_queue = asyncio.Queue() while True: received_msg = await sock.recv_multipart() if _DEBUG_: print("received:", received_msg) message_queue.put_nowait(received_msg.__str__()) message, receiver = await process_request(message_queue) if receiver is not None: await sock.send_multipart( [receiver.encode(), b"", message.encode()]) if _DEBUG_ == True: print("sent:", [receiver.encode(), b"", message.encode()]) elif message is not None: print(f'{message} connected.')
def __init__( self, ip: str, port: int, unpack=None, logger: logging.Logger = None, zmqcontext=None, loop=None, passoff_callback=None, name: str = None, ): """The init of an AsyncSubscriber Args: ip (str): The ip address where the datas are published (can be local or remote) port (int): The port number at which the datas are published unpack (None, optional): A callable which takes the received data packet as input and returns an unpacked object. If not given the packed data object is put in the subscribed buffer. logger (logging.Logger, optional): Optionally provide a logger instance zmqcontext (None, optional): zmq context loop (None, optional): an asyncio event loop passoff_callback (None, optional): An optional callback for overriding the default buffer. Note: if this is used then ``get_data()`` will always be empty. name (str, optional): The name of the subscriber (used in logging) """ logger = logger or sslogger name = name or __class__.__name__ self.log = logger.getChild(name) self._context = zmqcontext or zmq.asyncio.Context() self._sock = self._context.socket(zmq.SUB) self._sock.setsockopt(zmq.SUBSCRIBE, b"") con_str = "tcp://%s:%s" % (ip, port) if "0.0.0.0" == ip: self._sock.bind(con_str) else: self._sock.connect(con_str) self.log.info("Connected to : %s" % con_str) self._running = False self._data_buffer = asyncio.Queue() self._loop = loop or asyncio.get_event_loop() self._running = True self._unpack = (lambda x: x) if unpack is None else unpack self._task = self._loop.create_task(self.receive()) self._passoff_callback = passoff_callback or ( lambda x: self._loop.create_task(self._data_buffer.put(x)))
def __init__(self, logger_name): ServiceBase.__init__(self, logger_name) # subscribe market data self.deribitmd = self.ctx.socket(zmq.SUB) self.deribitmd.connect('tcp://localhost:9050') self.deribitmd.setsockopt_string(zmq.SUBSCRIBE, '') # request client for transaction self.deribittdreq = self.ctx.socket(zmq.REQ) self.deribittdreq.connect('tcp://localhost:9020') # subscribe transaction data self.deribittd = self.ctx.socket(zmq.SUB) self.deribittd.connect('tcp://localhost:9010') self.deribittd.setsockopt_string(zmq.SUBSCRIBE, '') # async queue to sequentially combine market data and tx data self.msg = asyncio.Queue()