Python zmq.REQ Examples

The following are 30 code examples of zmq.REQ(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module zmq , or try the search function .
Example #1
Source File: test_socket.py    From vnpy_crypto with MIT License 7 votes vote down vote up
def test_hwm(self):
        zmq3 = zmq.zmq_version_info()[0] >= 3
        for stype in (zmq.PUB, zmq.ROUTER, zmq.SUB, zmq.REQ, zmq.DEALER):
            s = self.context.socket(stype)
            s.hwm = 100
            self.assertEqual(s.hwm, 100)
            if zmq3:
                try:
                    self.assertEqual(s.sndhwm, 100)
                except AttributeError:
                    pass
                try:
                    self.assertEqual(s.rcvhwm, 100)
                except AttributeError:
                    pass
            s.close() 
Example #2
Source File: common_client.py    From script-languages with MIT License 6 votes vote down vote up
def __init__(self, client_name):
        """This function estabilish the connection to EXASolution"""
        self.z = z
        self.connection_id = 0
        self.req = z.exascript_request()
        self.rep = z.exascript_response()
        self.client_name = client_name
        self.zcontext = zmq.Context()
        self.zsocket = self.zcontext.socket(zmq.REQ)
        if self.client_name.startswith('tcp://'):
            self.zsocket.bind(self.client_name)
        elif self.client_name.startswith('unix://'):
            self.zsocket.connect(self.client_name)
        elif self.client_name.startswith('ipc://'):
            self.zsocket.connect(self.client_name)            
        else: raise RuntimeError("Unsupported protocol, supported are only ipc://, tcp://, and unix://") 
Example #3
Source File: shell.py    From networkzero with MIT License 6 votes vote down vote up
def main():
    context = zmq.Context()
    socket = context.socket(zmq.REQ)
    socket.connect("tcp://%s:%s" % (config.LISTEN_ON_IP, config.LISTEN_ON_PORT))

    while True:
        command = input("Command: ")
        socket.send(command.encode(config.CODEC))
        response = socket.recv().decode(config.CODEC)
        print("  ... %s" % response)
        words = shlex.split(response.lower())
        status = words[0]
        if len(words) > 1:
            info = words[1:]
        if status == "finished":
            print("Finished status received from robot")
            break 
Example #4
Source File: vnrpc.py    From vnpy_crypto with MIT License 6 votes vote down vote up
def __init__(self, reqAddress, subAddress):
        """Constructor"""
        super(RpcClient, self).__init__()
        
        # zmq端口相关
        self.__reqAddress = reqAddress
        self.__subAddress = subAddress
        
        self.__context = zmq.Context()
        self.__socketREQ = self.__context.socket(zmq.REQ)   # 请求发出socket
        self.__socketSUB = self.__context.socket(zmq.SUB)   # 广播订阅socket        

        # 工作线程相关,用于处理服务器推送的数据
        self.__active = False                                   # 客户端的工作状态
        self.__thread = threading.Thread(target=self.run)       # 客户端的工作线程
        
    #---------------------------------------------------------------------- 
Example #5
Source File: IVVIDIG_main_eth.py    From qkit with GNU General Public License v2.0 6 votes vote down vote up
def _open_zmq_connection(self):
        '''
        Connects to the raspberry via zmq/tcp

        Input:
            None

        Output:
            None
        '''
        
        self.context = zmq.Context(1)
        print("Connecting to Raspberry Pi")
        self.client = self.context.socket(zmq.REQ)
        self.client.connect("tcp://%s:%s"%(self._address,self._port)) # raspi address

        self.poll = zmq.Poller()
        self.poll.register(self.client, zmq.POLLIN) 
Example #6
Source File: datafeed.py    From cryptotrader with MIT License 6 votes vote down vote up
def __init__(self, exchange='', addr='ipc:///tmp/feed.ipc', timeout=30):
        """

        :param period: int: Data sampling period
        :param pairs: list: Pair symbols to trade
        :param exchange: str: FeedDaemon exchange to query
        :param addr: str: Client socked address
        :param timeout: int:
        """
        super(DataFeed, self).__init__()

        # Sock objects
        self.context = zmq.Context()
        self.addr = addr
        self.exchange = exchange
        self.timeout = timeout * 1000

        self.sock = self.context.socket(zmq.REQ)
        self.sock.connect(addr)

        self.poll = zmq.Poller()
        self.poll.register(self.sock, zmq.POLLIN) 
Example #7
Source File: test_device.py    From pySINDy with MIT License 6 votes vote down vote up
def test_single_socket_forwarder_connect(self):
        if zmq.zmq_version() in ('4.1.1', '4.0.6'):
            raise SkipTest("libzmq-%s broke single-socket devices" % zmq.zmq_version())
        dev = devices.ThreadDevice(zmq.QUEUE, zmq.REP, -1)
        req = self.context.socket(zmq.REQ)
        port = req.bind_to_random_port('tcp://127.0.0.1')
        dev.connect_in('tcp://127.0.0.1:%i'%port)
        dev.start()
        time.sleep(.25)
        msg = b'hello'
        req.send(msg)
        self.assertEqual(msg, self.recv(req))
        del dev
        req.close()
        dev = devices.ThreadDevice(zmq.QUEUE, zmq.REP, -1)
        req = self.context.socket(zmq.REQ)
        port = req.bind_to_random_port('tcp://127.0.0.1')
        dev.connect_out('tcp://127.0.0.1:%i'%port)
        dev.start()
        time.sleep(.25)
        msg = b'hello again'
        req.send(msg)
        self.assertEqual(msg, self.recv(req))
        del dev
        req.close() 
Example #8
Source File: test_monitor.py    From pySINDy with MIT License 6 votes vote down vote up
def test_monitor_connected(self):
        """Test connected monitoring socket."""
        s_rep = self.context.socket(zmq.REP)
        s_req = self.context.socket(zmq.REQ)
        self.sockets.extend([s_rep, s_req])
        s_req.bind("tcp://127.0.0.1:6667")
        # try monitoring the REP socket
        # create listening socket for monitor
        s_event = s_rep.get_monitor_socket()
        s_event.linger = 0
        self.sockets.append(s_event)
        # test receive event for connect event
        s_rep.connect("tcp://127.0.0.1:6667")
        m = recv_monitor_message(s_event)
        if m['event'] == zmq.EVENT_CONNECT_DELAYED:
            self.assertEqual(m['endpoint'], b"tcp://127.0.0.1:6667")
            # test receive event for connected event
            m = recv_monitor_message(s_event)
        self.assertEqual(m['event'], zmq.EVENT_CONNECTED)
        self.assertEqual(m['endpoint'], b"tcp://127.0.0.1:6667") 
Example #9
Source File: test_device.py    From vnpy_crypto with MIT License 6 votes vote down vote up
def test_single_socket_forwarder_connect(self):
        if zmq.zmq_version() in ('4.1.1', '4.0.6'):
            raise SkipTest("libzmq-%s broke single-socket devices" % zmq.zmq_version())
        dev = devices.ThreadDevice(zmq.QUEUE, zmq.REP, -1)
        req = self.context.socket(zmq.REQ)
        port = req.bind_to_random_port('tcp://127.0.0.1')
        dev.connect_in('tcp://127.0.0.1:%i'%port)
        dev.start()
        time.sleep(.25)
        msg = b'hello'
        req.send(msg)
        self.assertEqual(msg, self.recv(req))
        del dev
        req.close()
        dev = devices.ThreadDevice(zmq.QUEUE, zmq.REP, -1)
        req = self.context.socket(zmq.REQ)
        port = req.bind_to_random_port('tcp://127.0.0.1')
        dev.connect_out('tcp://127.0.0.1:%i'%port)
        dev.start()
        time.sleep(.25)
        msg = b'hello again'
        req.send(msg)
        self.assertEqual(msg, self.recv(req))
        del dev
        req.close() 
Example #10
Source File: test_monitor.py    From vnpy_crypto with MIT License 6 votes vote down vote up
def test_monitor_connected(self):
        """Test connected monitoring socket."""
        s_rep = self.context.socket(zmq.REP)
        s_req = self.context.socket(zmq.REQ)
        self.sockets.extend([s_rep, s_req])
        s_req.bind("tcp://127.0.0.1:6667")
        # try monitoring the REP socket
        # create listening socket for monitor
        s_event = s_rep.get_monitor_socket()
        s_event.linger = 0
        self.sockets.append(s_event)
        # test receive event for connect event
        s_rep.connect("tcp://127.0.0.1:6667")
        m = recv_monitor_message(s_event)
        if m['event'] == zmq.EVENT_CONNECT_DELAYED:
            self.assertEqual(m['endpoint'], b"tcp://127.0.0.1:6667")
            # test receive event for connected event
            m = recv_monitor_message(s_event)
        self.assertEqual(m['event'], zmq.EVENT_CONNECTED)
        self.assertEqual(m['endpoint'], b"tcp://127.0.0.1:6667") 
Example #11
Source File: vnrpc.py    From InplusTrader_Linux with MIT License 6 votes vote down vote up
def __init__(self, reqAddress, subAddress):
        """Constructor"""
        super(RpcClient, self).__init__()
        
        # zmq端口相关
        self.__reqAddress = reqAddress
        self.__subAddress = subAddress
        
        self.__context = zmq.Context()
        self.__socketREQ = self.__context.socket(zmq.REQ)   # 请求发出socket
        self.__socketSUB = self.__context.socket(zmq.SUB)   # 广播订阅socket        

        # 工作线程相关,用于处理服务器推送的数据
        self.__active = False                                   # 客户端的工作状态
        self.__thread = threading.Thread(target=self.run)       # 客户端的工作线程
        
    #---------------------------------------------------------------------- 
Example #12
Source File: mpinoseutils.py    From pyGSTi with Apache License 2.0 6 votes vote down vote up
def __init__(self, max_nprocs):
        import subprocess
        import sys
        import os
        import zmq

        # Since the output terminals are used for lots of debug output etc., we use
        # ZeroMQ to communicate with the workers.
        zctx = zmq.Context()
        socket = zctx.socket(zmq.REQ)
        port = socket.bind_to_random_port("tcp://*")
        cmd = 'import %s as mod; mod._mpi_worker("tcp://127.0.0.1:%d")' % (__name__, port)
        env = dict(os.environ)
        env['PYTHONPATH'] = ':'.join(sys.path)
        self.child = subprocess.Popen(['mpiexec', '-np', str(max_nprocs), sys.executable,
                                       '-c', cmd], env=env)
        self.socket = socket 
Example #13
Source File: test_socket.py    From pySINDy with MIT License 6 votes vote down vote up
def test_hwm(self):
        zmq3 = zmq.zmq_version_info()[0] >= 3
        for stype in (zmq.PUB, zmq.ROUTER, zmq.SUB, zmq.REQ, zmq.DEALER):
            s = self.context.socket(stype)
            s.hwm = 100
            self.assertEqual(s.hwm, 100)
            if zmq3:
                try:
                    self.assertEqual(s.sndhwm, 100)
                except AttributeError:
                    pass
                try:
                    self.assertEqual(s.rcvhwm, 100)
                except AttributeError:
                    pass
            s.close() 
Example #14
Source File: test_reqrep.py    From pySINDy with MIT License 5 votes vote down vote up
def test_basic(self):
        s1, s2 = self.create_bound_pair(zmq.REQ, zmq.REP)

        msg1 = b'message 1'
        msg2 = self.ping_pong(s1, s2, msg1)
        self.assertEqual(msg1, msg2) 
Example #15
Source File: pause_for_kernel.py    From ansible-jupyter-kernel with Apache License 2.0 5 votes vote down vote up
def run(self, tmp=None, task_vars=None):
        # print ('pause_for_kernel')
        if task_vars is None:
            task_vars = dict()
        host = self._task.args.get('host', None)
        port = self._task.args.get('port', None)
        task_num = self._task.args.get('task_num', None)
        # print (task_num)
        result = super(ActionModule, self).run(tmp, task_vars)

        context = zmq.Context()
        socket = context.socket(zmq.REQ)
        socket.setsockopt(zmq.LINGER, 0)
        # print ('connecting...')
        socket.connect("tcp://{0}:{1}".format(host, port))
        # print ('connected')
        # print ('sending...')
        socket.send_string("{0}".format(task_num))
        # print ('sent')
        # print ('waiting...')
        socket.recv()
        # print ('received')
        # print ('closing...')
        socket.close()
        # print ('closed')
        return result 
Example #16
Source File: broadcast_connector.py    From gateway with GNU Affero General Public License v3.0 5 votes vote down vote up
def next(self, timeout):
        if not self.queue:
            return
        self.current = self.queue.pop(0)
        msg = self.current[0]
        self.watchdog_task = reactor.callLater(timeout, self.watchdog)
        # new socket
        self.s = self.c.socket(zmq.REQ)
        self.s.connect(config.get("broadcaster-url", "tcp://localhost:9109"))
        self.s.send(msg)
        self.tries = 0
        self.receive() 
Example #17
Source File: p2p.py    From gateway with GNU Affero General Public License v3.0 5 votes vote down vote up
def create_socket(self):
        self._ctx = zmq.Context()
        self._socket = self._ctx.socket(zmq.REQ)
        self._socket.connect(self._address) 
Example #18
Source File: ZeroMQ_MT4_Python_Template.py    From DarwinexLabs with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def zeromq_mt4_ea_client():
    
    # Create ZMQ Context
    context = zmq.Context()
    
    # Create REQ Socket
    reqSocket = context.socket(zmq.REQ)
    reqSocket.connect("tcp://localhost:5555")
    
    # Create PULL Socket
    pullSocket = context.socket(zmq.PULL)
    pullSocket.connect("tcp://localhost:5556")
    
    # Send RATES command to ZeroMQ MT4 EA
    remote_send(reqSocket, get_rates)
        
    # Send BUY EURUSD command to ZeroMQ MT4 EA
    # remote_send(reqSocket, eurusd_buy_order)
    
    # Send CLOSE EURUSD command to ZeroMQ MT4 EA. You'll need to append the 
    # trade's ORDER ID to the end, as below for example:
    # remote_send(reqSocket, eurusd_closebuy_order + "|" + "12345678")
    
    # PULL from pullSocket
    remote_pull(pullSocket)
    
# Function to send commands to ZeroMQ MT4 EA 
Example #19
Source File: test_reqrep.py    From pySINDy with MIT License 5 votes vote down vote up
def test_pyobj(self):
        s1, s2 = self.create_bound_pair(zmq.REQ, zmq.REP)
        o = dict(a=10,b=range(10))
        o2 = self.ping_pong_pyobj(s1, s2, o) 
Example #20
Source File: test_reqrep.py    From pySINDy with MIT License 5 votes vote down vote up
def test_bad_send_recv(self):
        s1, s2 = self.create_bound_pair(zmq.REQ, zmq.REP)
        
        if zmq.zmq_version() != '2.1.8':
            # this doesn't work on 2.1.8
            for copy in (True,False):
                self.assertRaisesErrno(zmq.EFSM, s1.recv, copy=copy)
                self.assertRaisesErrno(zmq.EFSM, s2.send, b'asdf', copy=copy)

        # I have to have this or we die on an Abort trap.
        msg1 = b'asdf'
        msg2 = self.ping_pong(s1, s2, msg1)
        self.assertEqual(msg1, msg2) 
Example #21
Source File: remote_agent.py    From neural_chat with MIT License 5 votes vote down vote up
def __init__(self, opt, shared=None):
        """Runs subprocess command to set up remote partner.
        Only run the subprocess command once: if using multiple threads, tell
        the partner how many paired agents to set up so that they can manage
        the multithreading effectively in their environment. (We don't run
        subprocess.Popen for each thread.)
        """
        self.opt = copy.deepcopy(opt)
        self.address = opt['remote_address']
        if opt.get('remote_host') and self.address == 'localhost':
            self.address = '*'
        self.socket_type = zmq.REP if opt['remote_host'] else zmq.REQ
        if shared and 'port' in shared:
            # for multithreading, use specified port
            self.port = shared['port']
        else:
            if 'port' in opt:
                self.port = opt['port']
            else:
                raise RuntimeError(
                    'You need to run RemoteAgent.'
                    + 'add_cmdline_args(argparser) before '
                    + 'calling this class to set up options.'
                )
            if opt.get('remote_cmd'):
                # if available, command to launch partner instance, passing on
                # some shared parameters from ParlAI
                # useful especially if "remote" agent is running locally, e.g.
                # in a different language than python
                self.process = subprocess.Popen(
                    '{cmd} {port} {numthreads} {args}'.format(
                        cmd=opt['remote_cmd'],
                        port=opt['port'],
                        numthreads=opt['numthreads'],
                        args=opt.get('remote_args', ''),
                    ).split()
                )
        self.connect()
        super().__init__(opt, shared) 
Example #22
Source File: test_reqrep.py    From pySINDy with MIT License 5 votes vote down vote up
def test_multiple(self):
        s1, s2 = self.create_bound_pair(zmq.REQ, zmq.REP)

        for i in range(10):
            msg1 = i*b' '
            msg2 = self.ping_pong(s1, s2, msg1)
            self.assertEqual(msg1, msg2) 
Example #23
Source File: test_monitor.py    From pySINDy with MIT License 5 votes vote down vote up
def test_monitor(self):
        """Test monitoring interface for sockets."""
        s_rep = self.context.socket(zmq.REP)
        s_req = self.context.socket(zmq.REQ)
        self.sockets.extend([s_rep, s_req])
        s_req.bind("tcp://127.0.0.1:6666")
        # try monitoring the REP socket
        
        s_rep.monitor("inproc://monitor.rep", zmq.EVENT_ALL)
        # create listening socket for monitor
        s_event = self.context.socket(zmq.PAIR)
        self.sockets.append(s_event)
        s_event.connect("inproc://monitor.rep")
        s_event.linger = 0
        # test receive event for connect event
        s_rep.connect("tcp://127.0.0.1:6666")
        m = recv_monitor_message(s_event)
        if m['event'] == zmq.EVENT_CONNECT_DELAYED:
            self.assertEqual(m['endpoint'], b"tcp://127.0.0.1:6666")
            # test receive event for connected event
            m = recv_monitor_message(s_event)
        self.assertEqual(m['event'], zmq.EVENT_CONNECTED)
        self.assertEqual(m['endpoint'], b"tcp://127.0.0.1:6666")

        # test monitor can be disabled.
        s_rep.disable_monitor()
        m = recv_monitor_message(s_event)
        self.assertEqual(m['event'], zmq.EVENT_MONITOR_STOPPED) 
Example #24
Source File: test_device.py    From pySINDy with MIT License 5 votes vote down vote up
def test_green_device(self):
            rep = self.context.socket(zmq.REP)
            req = self.context.socket(zmq.REQ)
            self.sockets.extend([req, rep])
            port = rep.bind_to_random_port('tcp://127.0.0.1')
            g = gevent.spawn(zmq.green.device, zmq.QUEUE, rep, rep)
            req.connect('tcp://127.0.0.1:%i' % port)
            req.send(b'hi')
            timeout = gevent.Timeout(3)
            timeout.start()
            receiver = gevent.spawn(req.recv)
            self.assertEqual(receiver.get(2), b'hi')
            timeout.cancel()
            g.kill(block=True) 
Example #25
Source File: test_socket.py    From pySINDy with MIT License 5 votes vote down vote up
def test_warn_set_timeo(self):
            s = self.context.socket(zmq.REQ)
            with warnings.catch_warnings(record=True) as w:
                s.rcvtimeo = 5
            s.close()
            self.assertEqual(len(w), 1)
            self.assertEqual(w[0].category, UserWarning) 
Example #26
Source File: test_device.py    From pySINDy with MIT License 5 votes vote down vote up
def test_proxy(self):
        if zmq.zmq_version_info() < (3,2):
            raise SkipTest("Proxies only in libzmq >= 3")
        dev = devices.ThreadProxy(zmq.PULL, zmq.PUSH, zmq.PUSH)
        binder = self.context.socket(zmq.REQ)
        iface = 'tcp://127.0.0.1'
        port = binder.bind_to_random_port(iface)
        port2 = binder.bind_to_random_port(iface)
        port3 = binder.bind_to_random_port(iface)
        binder.close()
        time.sleep(0.1)
        dev.bind_in("%s:%i" % (iface, port))
        dev.bind_out("%s:%i" % (iface, port2))
        dev.bind_mon("%s:%i" % (iface, port3))
        dev.start()
        time.sleep(0.25)
        msg = b'hello'
        push = self.context.socket(zmq.PUSH)
        push.connect("%s:%i" % (iface, port))
        pull = self.context.socket(zmq.PULL)
        pull.connect("%s:%i" % (iface, port2))
        mon = self.context.socket(zmq.PULL)
        mon.connect("%s:%i" % (iface, port3))
        push.send(msg)
        self.sockets.extend([push, pull, mon])
        self.assertEqual(msg, self.recv(pull))
        self.assertEqual(msg, self.recv(mon)) 
Example #27
Source File: test_socket.py    From pySINDy with MIT License 5 votes vote down vote up
def test_warn_get_timeo(self):
            s = self.context.socket(zmq.REQ)
            with warnings.catch_warnings(record=True) as w:
                s.sndtimeo
            s.close()
            self.assertEqual(len(w), 1)
            self.assertEqual(w[0].category, UserWarning) 
Example #28
Source File: test_context.py    From pySINDy with MIT License 5 votes vote down vote up
def test_sockopts(self):
        """setting socket options with ctx attributes"""
        ctx = self.Context()
        ctx.linger = 5
        self.assertEqual(ctx.linger, 5)
        s = ctx.socket(zmq.REQ)
        self.assertEqual(s.linger, 5)
        self.assertEqual(s.getsockopt(zmq.LINGER), 5)
        s.close()
        # check that subscribe doesn't get set on sockets that don't subscribe:
        ctx.subscribe = b''
        s = ctx.socket(zmq.REQ)
        s.close()
        
        ctx.term() 
Example #29
Source File: test_context.py    From pySINDy with MIT License 5 votes vote down vote up
def test_term_noclose(self):
        """Context.term won't close sockets"""
        ctx = self.Context()
        s = ctx.socket(zmq.REQ)
        self.assertFalse(s.closed)
        t = Thread(target=ctx.term)
        t.start()
        t.join(timeout=0.1)
        self.assertTrue(t.is_alive(), "Context should be waiting")
        s.close()
        t.join(timeout=0.1)
        self.assertFalse(t.is_alive(), "Context should have closed") 
Example #30
Source File: test_ioloop.py    From pySINDy with MIT License 5 votes vote down vote up
def test_close_all(self):
        """Test close(all_fds=True)"""
        loop = self.IOLoop.current()
        req,rep = self.create_bound_pair(zmq.REQ, zmq.REP)
        loop.add_handler(req, lambda msg: msg, ioloop.IOLoop.READ)
        loop.add_handler(rep, lambda msg: msg, ioloop.IOLoop.READ)
        self.assertEqual(req.closed, False)
        self.assertEqual(rep.closed, False)
        loop.close(all_fds=True)
        self.assertEqual(req.closed, True)
        self.assertEqual(rep.closed, True)