本文整理汇总了Python中nanomsg.Socket类的典型用法代码示例。如果您正苦于以下问题:Python Socket类的具体用法?Python Socket怎么用?Python Socket使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Socket类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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)
示例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)
示例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)
示例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()
示例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)
示例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
示例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__()
示例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)
示例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
示例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
示例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')
示例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()
示例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)
示例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)
示例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