本文整理汇总了Python中nanomsg.Socket.connect方法的典型用法代码示例。如果您正苦于以下问题:Python Socket.connect方法的具体用法?Python Socket.connect怎么用?Python Socket.connect使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类nanomsg.Socket
的用法示例。
在下文中一共展示了Socket.connect方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: iogate
# 需要导入模块: from nanomsg import Socket [as 别名]
# 或者: from nanomsg.Socket import connect [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: _bg
# 需要导入模块: from nanomsg import Socket [as 别名]
# 或者: from nanomsg.Socket import connect [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)
示例3: register_service
# 需要导入模块: from nanomsg import Socket [as 别名]
# 或者: from nanomsg.Socket import connect [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))
示例4: TestGeneralSocketMethods
# 需要导入模块: from nanomsg import Socket [as 别名]
# 或者: from nanomsg.Socket import connect [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)
示例5: NanomsgSubscriber
# 需要导入模块: from nanomsg import Socket [as 别名]
# 或者: from nanomsg.Socket import connect [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()
示例6: sender
# 需要导入模块: from nanomsg import Socket [as 别名]
# 或者: from nanomsg.Socket import connect [as 别名]
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
示例7: slave_loop
# 需要导入模块: from nanomsg import Socket [as 别名]
# 或者: from nanomsg.Socket import connect [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
示例8: ConsoleProxy
# 需要导入模块: from nanomsg import Socket [as 别名]
# 或者: from nanomsg.Socket import connect [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)
示例9: main
# 需要导入模块: from nanomsg import Socket [as 别名]
# 或者: from nanomsg.Socket import connect [as 别名]
def main():
sift_root = init.env_var_or_exit('SIFT_ROOT')
ipc_root = init.env_var_or_exit('IPC_ROOT')
dag = load_dag(sift_root)
threads = {}
sockets = []
node_indexes = sys.argv[1:]
if len(node_indexes) == 0:
print('no nodes to execute')
return 1
dry = os.environ.get('DRY', 'false')
if dry == 'true':
return 0
for i in map(int, node_indexes):
src = os.path.join(sift_root, dag['dag']['nodes'][i]['implementation']['python'])
print('loading ' + src)
m = new_module(i, src)
# Create nanomsg socket.
addr = 'ipc://%s/%d.sock'% (ipc_root, i)
s = Socket(REP)
s.recv_max_size = -1
s.connect(addr)
print('connected to '+ addr)
sockets.append(s)
# Launch request handler.
t = threading.Thread(target=listen_and_reply, args=(s, m.compute))
t.daemon = True
t.start()
threads[i] = t
try:
while True:
time.sleep(1)
for i, thr in threads.items():
if not thr.isAlive():
raise Exception('thread of node with index %d is dead' % i)
finally:
print('closing sockets')
for s in sockets: s.close()
示例10: Client
# 需要导入模块: from nanomsg import Socket [as 别名]
# 或者: from nanomsg.Socket import connect [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)
示例11: nano_client
# 需要导入模块: from nanomsg import Socket [as 别名]
# 或者: from nanomsg.Socket import connect [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()
示例12: LogSub
# 需要导入模块: from nanomsg import Socket [as 别名]
# 或者: from nanomsg.Socket import connect [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
示例13: sender
# 需要导入模块: from nanomsg import Socket [as 别名]
# 或者: from nanomsg.Socket import connect [as 别名]
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
示例14: sender
# 需要导入模块: from nanomsg import Socket [as 别名]
# 或者: from nanomsg.Socket import connect [as 别名]
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
示例15: Socket
# 需要导入模块: from nanomsg import Socket [as 别名]
# 或者: from nanomsg.Socket import connect [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())