本文整理汇总了Python中nanomsg.Socket.bind方法的典型用法代码示例。如果您正苦于以下问题:Python Socket.bind方法的具体用法?Python Socket.bind怎么用?Python Socket.bind使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类nanomsg.Socket
的用法示例。
在下文中一共展示了Socket.bind方法的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: iogate
# 需要导入模块: from nanomsg import Socket [as 别名]
# 或者: from nanomsg.Socket import bind [as 别名]
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: nano_server
# 需要导入模块: from nanomsg import Socket [as 别名]
# 或者: from nanomsg.Socket import bind [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()
示例3: start_service
# 需要导入模块: from nanomsg import Socket [as 别名]
# 或者: from nanomsg.Socket import bind [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')
示例4: master_loop
# 需要导入模块: from nanomsg import Socket [as 别名]
# 或者: from nanomsg.Socket import bind [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)
示例5: receiver
# 需要导入模块: from nanomsg import Socket [as 别名]
# 或者: from nanomsg.Socket import bind [as 别名]
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
示例6: TestGeneralSocketMethods
# 需要导入模块: from nanomsg import Socket [as 别名]
# 或者: from nanomsg.Socket import bind [as 别名]
class TestGeneralSocketMethods(unittest.TestCase):
def setUp(self):
self.socket = Socket(PAIR)
def tearDown(self):
self.socket.close()
def test_bind(self):
endpoint = self.socket.bind(SOCKET_ADDRESS)
self.assertNotEqual(None, endpoint)
def test_connect(self):
endpoint = self.socket.connect(SOCKET_ADDRESS)
self.assertNotEqual(None, endpoint)
def test_is_open_is_true_when_open(self):
self.assertTrue(self.socket.is_open())
def test_is_open_is_false_when_closed(self):
self.socket.close()
self.assertFalse(self.socket.is_open())
def test_set_and_get_int_option(self):
expected = 500
self.socket.set_int_option(SOL_SOCKET, SNDBUF, expected)
actual = self.socket.get_int_option(SOL_SOCKET, SNDBUF)
self.assertEqual(expected, actual)
示例7: NanomsgPublisher
# 需要导入模块: from nanomsg import Socket [as 别名]
# 或者: from nanomsg.Socket import bind [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()
示例8: ServiceDiscovery
# 需要导入模块: from nanomsg import Socket [as 别名]
# 或者: from nanomsg.Socket import bind [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()
示例9: nano_sub
# 需要导入模块: from nanomsg import Socket [as 别名]
# 或者: from nanomsg.Socket import bind [as 别名]
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)
示例10: receiver
# 需要导入模块: from nanomsg import Socket [as 别名]
# 或者: from nanomsg.Socket import bind [as 别名]
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
示例11: Socket
# 需要导入模块: from nanomsg import Socket [as 别名]
# 或者: from nanomsg.Socket import bind [as 别名]
from __future__ import print_function
from nanomsg import Socket, PAIR, PUB
s1 = Socket(PAIR)
s2 = Socket(PAIR)
s1.bind('inproc://bob')
s2.connect('inproc://bob')
s1.send(b'hello nanomsg')
print(s2.recv())
s1.close()
s2.close()
with Socket(PAIR) as s3:
with Socket(PAIR) as s4:
s3.bind('inproc://demo')
s4.connect('inproc://demo')
s3.send('hi, I use "with"')
print(s4.recv())
s4.send('Ok, I see.')
print(s3.recv())
示例12: Daemon
# 需要导入模块: from nanomsg import Socket [as 别名]
# 或者: from nanomsg.Socket import bind [as 别名]
class Daemon(Common):
change_funcs = set()
bg_tasks = []
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()
def init(self):
pass
def recv(self):
msg = self.sock.recv()
# print "Received", self.load(msg)
return self.load(msg)
def send(self, *args):
msg = self.dump(*args)
return self.sock.send(msg)
def run(self):
t = Thread(target=self._bg)
t.start()
t = Thread(target=self._run)
t.start()
return t
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)
def handle_result(self, id, result):
print "Got result id=%r result=%r" % (id, result)
self.results[id] = result
self.send("ok")
def handle_setstate(self, key, value):
print "Set state key=%r value=%r" % (key, value)
self.state.set(key, value)
self.send("ok")
def handle_getstate(self, key):
value = self.state.get(key)
print "Get state key=%r value=%r" % (key, value)
self.send(value)
def handle_out(self, id, txt):
print "Got %s id=%r result=%r" % ("out", id, txt)
self.logs.append(id, "out", txt)
self.send("ok")
def handle_err(self, id, txt):
print "Got %s id=%r result=%r" % ("err", id, txt)
self.logs.append(id, "err", txt)
self.send("ok")
def handle_getresult(self, id):
result = self.results.get(id)
if result:
del self.results[id]
del self.threads[id]
print "sending result=%r for id=%r" % (result, id)
self.send(result)
def handle_getlog(self, id, since):
result = self.logs.get(id, since)
print "sending log=%r for id=%r" % (result, id)
self.send(result)
def _run(self):
while self.running:
(cmd, args) = self.recv()
func = getattr(self, "handle_" + cmd, None)
if func:
func(*args)
continue
t_id, t = self.spawn_worker(cmd, args)
self.send(t_id)
#.........这里部分代码省略.........