• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python nanomsg.Socket类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中nanomsg.Socket的典型用法代码示例。如果您正苦于以下问题:Python Socket类的具体用法?Python Socket怎么用?Python Socket使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了Socket类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: iogate

def iogate(type, queuein=Queue.Queue(), queueout=Queue.Queue(), network={}):
    sock = Socket(network['type'])
    
    if type == 'in':
      for port in network['ports']:
        sock.bind('tcp://0.0.0.0:{port}'.format(port=port))
    elif type == 'out':
      for node in network['nodes']:
        sock.connect('tcp://{ip}:{port}'.format(ip=node['ip'], 
                                                port=node['port']))
        
    def receive_messages():
        while True:
            queuein.put({'socket':in_sock, 'data': in_sock.recv()})
            print("Message received")
            
    def send_messages():
        while True:
            sock.send(queueout.get(block=True))
            print("Message has been sent")

    receiver = threading.Thread(target=receive_messages)
    sender = threading.Thread(target=send_messages)
    receiver.start()
    sender.start()
    
    return (queuein, queueout)
开发者ID:Zogg,项目名称:Tiltai,代码行数:27,代码来源:control.py


示例2: __init__

    def __init__(self, ui_event_engine, outgoing_quue):
        self._ui_event_engine = ui_event_engine
        self._outgoing_quue = outgoing_quue
        self._tick_sock = Socket(SUB)
        self._msg_sock = Socket(PAIR)

        self._active = False
        self._thread = Thread(target=self._run)
开发者ID:homeoffice-ys,项目名称:EliteQuant_Python,代码行数:8,代码来源:client_mq.py


示例3: main

def main():
    ap = argparse.ArgumentParser()
    ap.add_argument('-n', '--requests', metavar="NUM",
        help="Number of requests to issue (default %(default)d)",
        default=10000, type=int)
    ap.add_argument('-c', '--concurrent', metavar="NUM",
        help="Number of requests sent simultaneously (default %(default)d)",
        default=1000, type=int)
    ap.add_argument('-m', '--max-value', metavar="NUM",
        help="Maximum number that's sent for factorizing (default %(default)d)",
        default=10**12, type=int)
    ap.add_argument('--min-value', metavar="NUM",
        help="Maximum number that's sent for factorizing (default %(default)d)",
        default=10**11, type=int)
    ap.add_argument('--topology', metavar="URL", required=True,
        help="Url for topology to join to")
    options = ap.parse_args()

    sock = Socket(REQ, domain=AF_SP_RAW)
    sock.set_string_option(SOL_SOCKET, SOCKET_NAME, "client")
    sock.configure(options.topology)

    start_time = time.time()
    reqiter = requests(options)
    req = {}
    for i in range(options.concurrent):
        rid, val = next(reqiter)
        sock.send(b'\x00\x00\x00\x00' + struct.pack('>L', rid | 0x80000000)
            + str(val).encode('ascii'))
        req[rid] = val
    errors = 0
    sp  = 0
    n = 0
    while req:
        data = sock.recv()
        rid = struct.unpack_from('>L', data)[0] & ~0x80000000
        factors = map(int, data[4:].decode('ascii').split(','))
        checkval = reduce(int.__mul__, factors)
        if rid not in req:
            sp += 1
        elif req.pop(rid) != checkval:
            errors += 1
        else:
            n += 1

        try:
            rid, val = next(reqiter)
        except StopIteration:
            continue
        else:
            sock.send(b'\x00\x00\x00\x00' + struct.pack('>L', rid | 0x80000000)
                + str(val).encode('ascii'))
            req[rid] = val

    sec = time.time() - start_time
    print("Done", options.requests, "requests in", sec,
          "seconds, errors:", errors, ", spurious messages:", sp)
开发者ID:nanomsg,项目名称:nanomsg-integration-tests,代码行数:57,代码来源:factor_req.py


示例4: nano_server

def nano_server(endpoint):
    s = Socket(PAIR)
    s.bind('ipc://' + endpoint)
    #s.bind('tcp://127.0.0.1:9001')
    try:
        while True:
            s.recv()
            s.send('ok')
    finally:
        s.close()
开发者ID:LatitudeEngineering,项目名称:pmux,代码行数:10,代码来源:perf_nanomsg.py


示例5: master_loop

def master_loop():
    sock_slave = Socket(PAIR)
    sock_slave.bind('tcp://*:%s' % MASTER_PORT)
    sock_slave.recv_timeout = 250
    #sock_slave.send_buffer_size = 1000
    sock_slave.send_timeout = 200
    seq = 0

    timer = LightTimer()
    server = Server()

    while True:
        ch, value = chanselect([timer.chan, server.chan], [])
        #print 'AFTER chanselect', ch is timer.chan, time.time()
        if ch is timer.chan:
            lights.only(*value)
            #print "LIGHTS", value
            try:
                seq += 1
                sock_slave.send('%i %s %s' % (
                    seq,
                    CMD_LIGHTS,
                    ' '.join(lights.rev_lookup[led_pin] for led_pin in value)))
            except Exception as ex:
                #print ex
                pass
        elif ch is server.chan:
            if value[0] == 'status':
                slave = None
                try:
                    seq += 1
                    sock_slave.send('%i PING' % seq)
                    while True:
                        slave_msg = sock_slave.recv().split()
                        if int(slave_msg[0]) == seq:
                            slave = 'ok'
                            break
                        elif int(slave_msg[0]) > seq:
                            raise Exception('Skipped ping message')
                except Exception as ex:
                    slave = repr(ex)
                value[1].put({'loop': 'ok', 'slave': slave})
            elif value[0] == 'set_period':
                timer.period = value[1]
            elif value[0] == 'trip':
                timer.trip = True
            else:
                print "UNKNOWN COMMAND:", value
    time.sleep(2)
开发者ID:stuglaser,项目名称:trafficlights,代码行数:49,代码来源:traffic.py


示例6: receiver

def receiver(queue, ports, stype=SUB):
    in_sock = Socket(stype)
    
    for port in ports:
      in_sock.bind('tcp://0.0.0.0:{port}'.format(port=port))
    
    def receive_messages():
        while True:
            queue.put(in_sock.recv())
            print("Message received")

    receiver = threading.Thread(target=receive_messages)
    receiver.start()
    
    return in_sock
开发者ID:Zogg,项目名称:Tiltai,代码行数:15,代码来源:control.py


示例7: __init__

    def __init__(self, url, recv_timeout=1000, send_timeout=1000):
        self.url = url.encode()
        self.socket = Socket(REQ)

        self.socket.recv_timeout = recv_timeout
        self.socket.send_timeout = send_timeout

        super(ConsoleProxy, self).__init__()
开发者ID:cyberegoorg,项目名称:cetech,代码行数:8,代码来源:consoleproxy.py


示例8: main

def main():
    ap = argparse.ArgumentParser()
    ap.add_argument('-n', '--rate-limit', metavar="NUM",
        help="Number of requests to issue per second (default %(default)d)",
        default=100, type=float)
    ap.add_argument('-m', '--max-value', metavar="NUM",
        help="Maximum number that's sent for factorizing (default %(default)d)",
        default=10**12, type=int)
    ap.add_argument('--min-value', metavar="NUM",
        help="Maximum number that's sent for factorizing (default %(default)d)",
        default=10**11, type=int)
    ap.add_argument('--topology', metavar="URL", required=True,
        help="Url for topology to join to")
    options = ap.parse_args()

    delay = 1.0 / options.rate_limit
    sock = Socket(PUSH)
    sock.set_string_option(SOL_SOCKET, SOCKET_NAME, "push")
    sock.configure(options.topology)

    while True:
        tm = time.time()
        num = random.randint(options.min_value, options.max_value)
        sock.send(str(num))
        to_sleep = tm + delay - time.time()
        if to_sleep > 0:
            time.sleep(to_sleep)
开发者ID:nanomsg,项目名称:nanomsg-integration-tests,代码行数:27,代码来源:gen_numbers.py


示例9: sender

def sender(queue, network, stype=PUSH):
    out_sock = Socket(stype)

    for node in network['nodes']:
      print('tcp://{ip}:{port}'.format(ip=node['ip'], 
                                                  port=node['port']))
      out_sock.connect('tcp://{ip}:{port}'.format(ip=node['ip'], 
                                                  port=node['port']))

    def send_messages():
        while True:
            out_sock.send(queue.get(block=True))
            print("Message has been sent")

    receiver = threading.Thread(target=send_messages)
    receiver.start()

    return out_sock
开发者ID:Zogg,项目名称:Tiltai,代码行数:18,代码来源:control.py


示例10: sender

def sender(queue, addresses, stype):
    """
    Bind a queue to a connecting nanomsg socket's multiple endpoints
    in a separate thread.
    
    Parameters
    ----------
    queue : Queue
        A Queue object to be emptied by sender socket
        
    addresses : list
        A list of strings of format '<protocol>://<ip>:<port>' to bind to
        
    stype : int
        One of the nanomsg scalability socket types: PUSH, PULL, PUB, SUB, PAIR
        
    Returns
    -------
        nanomsg socket object
    """
    with err.applicationbound():
      out_sock = Socket(stype)
      
      out_sock.set_int_option(SOL_SOCKET, SNDTIMEO, 1000)
      
      for address in addresses:
          endpoint = out_sock.connect(address)
          out_endpoints.append(endpoint)
        
      def send_messages():
          """ """
          while True:
              try:
                  out_sock.send(queue.get(block=True))
                  log.info("Message has been sent")
              except NanoMsgAPIError as e:
                  log.debug(e)
                  log.debug(dir(e))
                  

      receiver = threading.Thread(target=send_messages)
      receiver.start()

      return out_sock
开发者ID:Zogg,项目名称:Tiltai,代码行数:44,代码来源:nanolink.py


示例11: __init__

    def __init__(self, url, topic):
        """ Initializes object

            Args:
                url (String): url to publish messages to
                topic (String): Topic to publish messages under
        """
        super(NanomsgPublisher, self).__init__(topic)
        self._socket = Socket(PUB)
        self._socket.send_timeout = 1 # Wait 1ms for sending
        self._socket.bind(url)
        self._logger = logging.getLogger('NanomsgPublisher')
开发者ID:PaddyK,项目名称:biosi,代码行数:12,代码来源:nanomsgcomponents.py


示例12: ServiceDiscovery

class ServiceDiscovery(object):
 
    def __init__(self, port, deadline=5000):
        self.socket = Socket(SURVEYOR)
        self.port = port
        self.deadline = deadline
        self.services = defaultdict(set)
 
    def bind(self):
        self.socket.bind('tcp://172.30.42.174:%s' % self.port)
        self.socket.set_int_option(SURVEYOR, SURVEYOR_DEADLINE, self.deadline)
 
    def discover(self):
        if not self.socket.is_open():
            return self.services
 
        self.services = defaultdict(set)
        self.socket.send('service query')
 
        while True:
            try:
                response = self.socket.recv()
            except NanoMsgAPIError:
                break
 
            service, address = response.split('|')
            self.services[service].add(address)
 
        return self.services
 
    def resolve(self, service):
        providers = self.services[service]
 
        if not providers:
            return None
 
        return random.choice(tuple(providers))
 
    def close(self):
        self.socket.close()
开发者ID:marchon,项目名称:upush,代码行数:40,代码来源:NanoServiceDiscovery.py


示例13: nano_sub

def nano_sub(bind, tables):
    """Nanomsg fanout subscriber. (Experimental)

    This subscriber will use nanomsg to publish the event to outside.
    """
    logger = logging.getLogger("meepo.sub.nano_sub")

    from nanomsg import Socket, PUB

    pub_socket = Socket(PUB)
    pub_socket.bind(bind)

    def _sub(table):
        for action in ("write", "update", "delete"):
            def _sub(pk, action=action):
                msg = bytes("%s_%s %s" % (table, action, pk), 'utf-8')
                logger.debug("pub msg %s" % msg)
                pub_socket.send(msg)

            signal("%s_%s" % (table, action)).connect(_sub, weak=False)

    for table in set(tables):
        _sub(table)
开发者ID:svisser,项目名称:meepo,代码行数:23,代码来源:sub.py


示例14: _bg

 def _bg(self):
     sock = Socket(REQ)
     sock.connect("inproc://server")
     while self.running:
         for func in self.bg_tasks:
             msg = self.dump((func, []))
             sock.send(msg)
             self.load(sock.recv())
         time.sleep(10)
开发者ID:JustinAzoff,项目名称:apitest,代码行数:9,代码来源:app.py


示例15: LogSub

class LogSub(QThread):
    def __init__(self, url):
        self.socket = Socket(SUB)
        self.url = url
        self.handlers = []

        super().__init__()

    def register_handler(self, handler):
        self.handlers.append(handler)

    def run(self):
        self.socket.set_string_option(SUB, SUB_SUBSCRIBE, b'')
        self.socket.connect(self.url)
        while True:
            try:
                msg = self.socket.recv()
                msg_pack = msgpack.unpackb(msg, encoding='utf-8')

                for h in self.handlers:
                    h(**msg_pack)

            except nanomsg.NanoMsgAPIError as e:
                raise
开发者ID:cyberegoorg,项目名称:cetech,代码行数:24,代码来源:logwidget.py


示例16: sender

def sender(queue, network, stype=PUSH):
    out_sock = Socket(stype)
    
    out_sock.set_int_option(SOL_SOCKET, SNDTIMEO, 1000)
    
    for node in network['nodes']:
        endpoint = out_sock.connect('tcp://{ip}:{port}'.format(ip=node['ip'], 
                                                               port=node['port']))
        out_endpoints.append(endpoint)
      
    def send_messages():
        while True:
            try:
                out_sock.send(queue.get(block=True))
                print("Message has been sent")
            except NanoMsgAPIError as e:
                print(e)
                print(dir(e))
                

    receiver = threading.Thread(target=send_messages)
    receiver.start()

    return out_sock
开发者ID:Zogg,项目名称:Tiltai,代码行数:24,代码来源:control.py


示例17: receiver

def receiver(queue, addresses, stype):
    """
    Bind a queue to a listening nanomsg socket's multiple endpoints
    in a separate thread.
    
    Parameters
    ----------
    queue : Queue
        A Queue object to be filled by receiver socket
        
    addresses : list
        A list of strings of format '<protocol>://<ip>:<port>' to bind to
        
    stype : int
        One of the nanomsg scalability socket types: PUSH, PULL, PUB, SUB, PAIR
        
    Returns
    -------
        nanomsg socket object
    """
    with err.applicationbound():
      in_sock = Socket(stype)
      
      for address in addresses:
        in_sock.bind(address)
      
      def receive_messages():
          """ """
          while True:
              queue.put(in_sock.recv())
              log.info("Message received")

      receiver = threading.Thread(target=receive_messages)
      receiver.start()
      
      return in_sock
开发者ID:Zogg,项目名称:Tiltai,代码行数:36,代码来源:nanolink.py


示例18: start_service

def start_service(service_name, service_protocol, service_port):
    socket = Socket(REP)
    socket.bind('%s://*:%s' % (service_protocol, service_port))

    print 'Starting service %s' % service_name

    while True:
        request = socket.recv()
        print 'Request: %s' % request
        socket.send('The answer is 42')
开发者ID:ming86,项目名称:nanomsg-service-discovery,代码行数:10,代码来源:serviced.py


示例19: register_service

def register_service(service_name, service_address, discovery_host,
                     discovery_port):
    socket = Socket(RESPONDENT)
    socket.connect('tcp://%s:%s' % (discovery_host, discovery_port))

    print 'Starting service registration [service: %s %s, discovery: %s:%s]' \
        % (service_name, service_address, discovery_host, discovery_port)

    while True:
        message = socket.recv()
        if message == 'service query':
            socket.send('%s|%s' % (service_name, service_address))
开发者ID:ming86,项目名称:nanomsg-service-discovery,代码行数:12,代码来源:serviced.py


示例20: __init__

    def __init__(self, state, logs, worker_class):
        self.state = state
        self.logs = logs
        self.worker_class = worker_class

        self.sock = Socket(REP)
        self.sock.bind("inproc://server")
        self.sock.bind("ipc://socket")

        self.results = {}
        self.threads = {}
        self.running = True

        self.change_lock = Lock()

        self.id_gen = iter(range(10000000)).next

        self.init()
开发者ID:JustinAzoff,项目名称:apitest,代码行数:18,代码来源:app.py



注:本文中的nanomsg.Socket类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python nanpy.Arduino类代码示例发布时间:2022-05-27
下一篇:
Python namespaces.get_twill_glocals函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap