当前位置: 首页>>代码示例>>Python>>正文


Python Socket.send方法代码示例

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


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

示例1: main

# 需要导入模块: from nanomsg import Socket [as 别名]
# 或者: from nanomsg.Socket import send [as 别名]
def main():
    ap = argparse.ArgumentParser()
    gr = ap.add_mutually_exclusive_group()
    gr.add_argument('--rep', metavar="URL",
        help="The topology url of replier socket")
    gr.add_argument('--pullpush', metavar="URL", nargs=2,
        help="The topology urls of pull and push sockets for request processing")
    options = ap.parse_args()

    if options.rep:
        sock = Socket(REP)
        sock.configure(options.rep)
        sock.set_string_option(SOL_SOCKET, SOCKET_NAME, "rep")
        read = write = sock
    else:
        read = Socket(PULL)
        read.set_string_option(SOL_SOCKET, SOCKET_NAME, "pull")
        write = Socket(PUSH)
        write.set_string_option(SOL_SOCKET, SOCKET_NAME, "push")

        read.configure(options.pullpush[0])
        write.configure(options.pullpush[1])


    while True:
        num = int(read.recv())
        res = factorize_naive(num)
        formula = str(num) + '=' + '*'.join(map(str, res))
        write.send(formula.encode('ascii'))
开发者ID:nanomsg,项目名称:nanomsg-integration-tests,代码行数:31,代码来源:factor_processor.py

示例2: main

# 需要导入模块: from nanomsg import Socket [as 别名]
# 或者: from nanomsg.Socket import send [as 别名]
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,代码行数:29,代码来源:gen_numbers.py

示例3: _bg

# 需要导入模块: from nanomsg import Socket [as 别名]
# 或者: from nanomsg.Socket import send [as 别名]
 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,代码行数:11,代码来源:app.py

示例4: main

# 需要导入模块: from nanomsg import Socket [as 别名]
# 或者: from nanomsg.Socket import send [as 别名]
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,代码行数:59,代码来源:factor_req.py

示例5: nano_server

# 需要导入模块: from nanomsg import Socket [as 别名]
# 或者: from nanomsg.Socket import send [as 别名]
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,代码行数:12,代码来源:perf_nanomsg.py

示例6: start_service

# 需要导入模块: from nanomsg import Socket [as 别名]
# 或者: from nanomsg.Socket import send [as 别名]
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,代码行数:12,代码来源:serviced.py

示例7: register_service

# 需要导入模块: from nanomsg import Socket [as 别名]
# 或者: from nanomsg.Socket import send [as 别名]
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,代码行数:14,代码来源:serviced.py

示例8: master_loop

# 需要导入模块: from nanomsg import Socket [as 别名]
# 或者: from nanomsg.Socket import send [as 别名]
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,代码行数:51,代码来源:traffic.py

示例9: slave_loop

# 需要导入模块: from nanomsg import Socket [as 别名]
# 或者: from nanomsg.Socket import send [as 别名]
def slave_loop(master):
    sock_master = Socket(PAIR)
    sock_master.connect('tcp://%s:%s' % (master, MASTER_PORT))

    while True:
        msg = sock_master.recv()
        #print 'HEARD', msg
        bits = msg.split()
        msgid = bits[0]
        cmd = bits[1]

        if cmd == CMD_PING:
            sock_master.send('%s PONG' % msgid)
        elif cmd == CMD_LIGHTS:
            which_pins = [lights.lookup[lgt] for lgt in bits[2:]]
            lights.only(*which_pins)
        else:
            print 'Unhandleable message: %r' % msg
开发者ID:stuglaser,项目名称:trafficlights,代码行数:20,代码来源:traffic.py

示例10: ConsoleProxy

# 需要导入模块: from nanomsg import Socket [as 别名]
# 或者: from nanomsg.Socket import send [as 别名]
class ConsoleProxy(object):
    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__()

    def connect(self):
        self.socket.connect(self.url)

    def disconnect(self):
        self.socket.close()

    def send_command(self, cmd_name, echo=True, **kwargs):
        command = {
            "name": cmd_name,
            "args": kwargs
        }

        dump = msgpack.packb(command)

        if echo:
            print('send: ', command)

        try:
            self.socket.send(dump)
        except NanoMsgAPIError as e:
            print('send_error', e.msg)
            pass

        try:
            recv = self.socket.recv()
            unpack_msg = msgpack.unpackb(recv, encoding='utf-8')

            if echo:
                print('recv: ', recv)
                print(unpack_msg)

            return unpack_msg
        except NanoMsgAPIError as e:
            print('recv_error', e.msg)
开发者ID:cyberegoorg,项目名称:cetech,代码行数:46,代码来源:consoleproxy.py

示例11: NanomsgPublisher

# 需要导入模块: from nanomsg import Socket [as 别名]
# 或者: from nanomsg.Socket import send [as 别名]
class NanomsgPublisher(HiddenPublisher):
    """ Publisher class publishing messages to a certain topic to an url

        Attributes:
            context (zmq.Context):
            socket (Socket): Socket object of ZMQ context
            topic (String): Topic publisher publishs to
    """
    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')

    def publish(self, message):
        """ Publishes message

            Args:
                message (String): Message to publish
        """
        self._socket.send('{}|{}'.format(self._topic, message))

    def __enter__(self):
        """ Statement used for the `` with ... as ...:`` returns
            the object to use in the ``with`` block

            Returns:
                NanomsgPublisher
        """
        return self

    def __exit__(self, exc_type, exc_value, traceback):
        """ Executed when leaving ``with`` block, regardless whether
            because of an exception or normal program flow
        """
        self._socket.close()
开发者ID:PaddyK,项目名称:biosi,代码行数:45,代码来源:nanomsgcomponents.py

示例12: Client

# 需要导入模块: from nanomsg import Socket [as 别名]
# 或者: from nanomsg.Socket import send [as 别名]
class Client(Common):
    def __init__(self, uri="inproc://server", id=None):
        self.sock = Socket(REQ)
        self.sock.connect(uri)
        self.id = id

    def close(self):
        self.sock.close()

    def call(self, func, *args):
        msg = self.dump((func, args))
        self.sock.send(msg)
        return self.load(self.sock.recv())

    def sync_call(self, func, *args):
        id = self.call(func, *args)
        print "got id", id
        while True:
            res = self.getresult(id)
            if res:
                return res
            time.sleep(0.1)

    def result(self, id, result):
        return self.call("result", id, result)

    def getresult(self, id):
        return self.call("getresult", id)

    def getstate(self, key):
        return self.call("getstate", key)

    def setstate(self, key, value):
        return self.call("setstate", key, value)

    def getlog(self, id, since=0):
        return self.call("getlog", id, since)

    def out(self, msg):
        return self.call("out", self.id, msg)

    def err(self, msg):
        return self.call("err", self.id, msg)
开发者ID:JustinAzoff,项目名称:apitest,代码行数:45,代码来源:app.py

示例13: ServiceDiscovery

# 需要导入模块: from nanomsg import Socket [as 别名]
# 或者: from nanomsg.Socket import send [as 别名]
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,代码行数:42,代码来源:NanoServiceDiscovery.py

示例14: nano_client

# 需要导入模块: from nanomsg import Socket [as 别名]
# 或者: from nanomsg.Socket import send [as 别名]
def nano_client(endpoint):
    s = Socket(PAIR)
    s.connect('ipc://' + endpoint)
    #s.connect('tcp://127.0.0.1:9001')
    count = 0

    payload = test_str(SIZE)

    start = time.time()
    try:
        while True:
            s.send(payload)
            s.recv()
            count += 1
    except:
        pass
    finally:
        end = time.time()
        total = end - start
        print 'total: ', count
        print 'took: ', total
        print 'req / sec:', count / total
        print 'bandwidth: %f MBps' % (((count / total) * SIZE) / 2 ** 20)
        s.close()
开发者ID:LatitudeEngineering,项目名称:pmux,代码行数:26,代码来源:perf_nanomsg.py

示例15: ClientMq

# 需要导入模块: from nanomsg import Socket [as 别名]
# 或者: from nanomsg.Socket import send [as 别名]
class ClientMq(object):
    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)

    def _run(self):
        while self._active:
            try:
                msg1 = self._tick_sock.recv(flags=1)
                msg1 = msg1.decode("utf-8")
                if msg1 is not None and msg1.index('|') > 0:
                    if msg1[-1] == '\0':
                        msg1 = msg1[:-1]
                    k = TickEvent()
                    k.deserialize(msg1)

                    self._ui_event_engine.put(k)
            except Exception as e:
                pass

            try:
                msg2 = self._msg_sock.recv(flags=1)
                msg2 = msg2.decode("utf-8")
                if msg2 is not None and msg2.index('|') > 0:
                    if msg2[-1] == '\0':
                        msg2 = msg2[:-1]
                    if msg2[-1] == '\x00':
                        msg2 = msg2[:-1]

                    v = msg2.split('|')
                    if v[0] == 's':
                       m = OrderStatusEvent()
                       m.deserialize(msg2)
                       self._ui_event_engine.put(m)
                    elif v[0] == 'f':
                        m = FillEvent()
                        m.deserialize(msg2)
                        self._ui_event_engine.put(m)
                    elif v[0] == 'n':
                        m = PositionEvent()
                        m.deserialize(msg2)
                        self._ui_event_engine.put(m)
                    elif v[0] == 'h':
                        m = HistoricalEvent()
                        m.deserialize(msg2)
                        self._ui_event_engine.put(m)
                    elif v[0] == 'u':
                        m = AccountEvent()
                        m.deserialize(msg2)
                        self._ui_event_engine.put(m)
                    elif v[0] == 'r':
                        m = ContractEvent()
                        m.deserialize(msg2)
                        self._ui_event_engine.put(m)
                    elif v[0] == 'm':
                        m = GeneralEvent()
                        m.deserialize(msg2)
                        self._ui_event_engine.put(m)
                        pass

            except Exception as e:
                pass
                # print('PAIR error: '+ str(i) + '' + str(e));
                # time.sleep(1)

            try:
                msg3 = self._outgoing_quue.get(False)
                self._msg_sock.send(msg3, flags=1)
            except Exception as e:
                pass

    def start(self, timer=True):
        """
        start the mq thread
        """
        self._tick_sock.connect('tcp://127.0.0.1:55555')
        self._tick_sock.set_string_option(SUB, SUB_SUBSCRIBE, '')  # receive msg start with all

        self._msg_sock.connect('tcp://127.0.0.1:55558')
        self._active = True

        if not self._thread.isAlive():
            self._thread.start()

    def stop(self):
        """
        stop the mq thread
        """
        self._active = False

        if self._thread.isAlive():
            self._thread.join()
开发者ID:homeoffice-ys,项目名称:EliteQuant_Python,代码行数:99,代码来源:client_mq.py


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