本文整理汇总了Python中nanomsg.Socket.recv方法的典型用法代码示例。如果您正苦于以下问题:Python Socket.recv方法的具体用法?Python Socket.recv怎么用?Python Socket.recv使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类nanomsg.Socket
的用法示例。
在下文中一共展示了Socket.recv方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: nano_server
# 需要导入模块: from nanomsg import Socket [as 别名]
# 或者: from nanomsg.Socket import recv [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()
示例2: main
# 需要导入模块: from nanomsg import Socket [as 别名]
# 或者: from nanomsg.Socket import recv [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'))
示例3: _bg
# 需要导入模块: from nanomsg import Socket [as 别名]
# 或者: from nanomsg.Socket import recv [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)
示例4: main
# 需要导入模块: from nanomsg import Socket [as 别名]
# 或者: from nanomsg.Socket import recv [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)
示例5: start_service
# 需要导入模块: from nanomsg import Socket [as 别名]
# 或者: from nanomsg.Socket import recv [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')
示例6: register_service
# 需要导入模块: from nanomsg import Socket [as 别名]
# 或者: from nanomsg.Socket import recv [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))
示例7: master_loop
# 需要导入模块: from nanomsg import Socket [as 别名]
# 或者: from nanomsg.Socket import recv [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)
示例8: nano_client
# 需要导入模块: from nanomsg import Socket [as 别名]
# 或者: from nanomsg.Socket import recv [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()
示例9: main
# 需要导入模块: from nanomsg import Socket [as 别名]
# 或者: from nanomsg.Socket import recv [as 别名]
def main():
ap = argparse.ArgumentParser()
ap.add_argument('--topology', metavar="URL", required=True,
help="Url for topology to join to")
options = ap.parse_args()
sock = Socket(PULL)
sock.set_string_option(SOL_SOCKET, SOCKET_NAME, "push")
sock.configure(options.topology)
while True:
data = sock.recv()
num, factors = data.decode('ascii').split('=', 1)
factors = map(int, factors.split('*'))
checkval = reduce(int.__mul__, factors)
assert int(num) == checkval
示例10: NanomsgSubscriber
# 需要导入模块: from nanomsg import Socket [as 别名]
# 或者: from nanomsg.Socket import recv [as 别名]
class NanomsgSubscriber(HiddenSubscriber):
""" Subscriber class subscribing to a certain topic
Attributes:
context (zmq.Context):
socket (Socket): Socket object of ZMQ context
topic (String): Topic subscriber subscribes to
"""
def __init__(self, url, topic):
""" Initializes object
Args:
url (String): url to publish messages to
topic (String): Topic to publish messages under
"""
super(NanomsgSubscriber, self).__init__(topic)
self._socket = Socket(SUB)
self._socket.recv_timeout = 500 # Wait 500ms for receiving msgs
self._socket.connect(url)
self._socket.set_string_option(SUB, SUB_SUBSCRIBE, topic + '|')
self._logger = logging.getLogger('NanomsgSubscriber')
def receive(self):
""" Receives a message
Returns:
String
"""
message = self._socket.recv()
return message[len(self.topic) + 1:]
def __enter__(self):
""" Statement used for the `` with ... as ...:`` returns
the object to use in the ``with`` block
Returns:
NanomsgSubscriber
"""
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()
示例11: slave_loop
# 需要导入模块: from nanomsg import Socket [as 别名]
# 或者: from nanomsg.Socket import recv [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
示例12: ConsoleProxy
# 需要导入模块: from nanomsg import Socket [as 别名]
# 或者: from nanomsg.Socket import recv [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)
示例13: Client
# 需要导入模块: from nanomsg import Socket [as 别名]
# 或者: from nanomsg.Socket import recv [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)
示例14: ServiceDiscovery
# 需要导入模块: from nanomsg import Socket [as 别名]
# 或者: from nanomsg.Socket import recv [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()
示例15: LogSub
# 需要导入模块: from nanomsg import Socket [as 别名]
# 或者: from nanomsg.Socket import recv [as 别名]
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