本文整理汇总了Python中zmq.NOBLOCK属性的典型用法代码示例。如果您正苦于以下问题:Python zmq.NOBLOCK属性的具体用法?Python zmq.NOBLOCK怎么用?Python zmq.NOBLOCK使用的例子?那么恭喜您, 这里精选的属性代码示例或许可以为您提供帮助。您也可以进一步了解该属性所在类zmq
的用法示例。
在下文中一共展示了zmq.NOBLOCK属性的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _handle_recv
# 需要导入模块: import zmq [as 别名]
# 或者: from zmq import NOBLOCK [as 别名]
def _handle_recv(self):
"""Handle a recv event."""
if self._flushed:
return
try:
msg = self.socket.recv_multipart(zmq.NOBLOCK, copy=self._recv_copy)
except zmq.ZMQError as e:
if e.errno == zmq.EAGAIN:
# state changed since poll event
pass
else:
raise
else:
if self._recv_callback:
callback = self._recv_callback
self._run_callback(callback, msg)
示例2: build_device
# 需要导入模块: import zmq [as 别名]
# 或者: from zmq import NOBLOCK [as 别名]
def build_device(self, mon_sub=b"", in_prefix=b'in', out_prefix=b'out'):
self.device = devices.ThreadMonitoredQueue(zmq.PAIR, zmq.PAIR, zmq.PUB,
in_prefix, out_prefix)
alice = self.context.socket(zmq.PAIR)
bob = self.context.socket(zmq.PAIR)
mon = self.context.socket(zmq.SUB)
aport = alice.bind_to_random_port('tcp://127.0.0.1')
bport = bob.bind_to_random_port('tcp://127.0.0.1')
mport = mon.bind_to_random_port('tcp://127.0.0.1')
mon.setsockopt(zmq.SUBSCRIBE, mon_sub)
self.device.connect_in("tcp://127.0.0.1:%i"%aport)
self.device.connect_out("tcp://127.0.0.1:%i"%bport)
self.device.connect_mon("tcp://127.0.0.1:%i"%mport)
self.device.start()
time.sleep(.2)
try:
# this is currenlty necessary to ensure no dropped monitor messages
# see LIBZMQ-248 for more info
mon.recv_multipart(zmq.NOBLOCK)
except zmq.ZMQError:
pass
self.sockets.extend([alice, bob, mon])
return alice, bob, mon
示例3: test_root_topic
# 需要导入模块: import zmq [as 别名]
# 或者: from zmq import NOBLOCK [as 别名]
def test_root_topic(self):
logger, handler, sub = self.connect_handler()
handler.socket.bind(self.iface)
sub2 = sub.context.socket(zmq.SUB)
self.sockets.append(sub2)
sub2.connect(self.iface)
sub2.setsockopt(zmq.SUBSCRIBE, b'')
handler.root_topic = b'twoonly'
msg1 = 'ignored'
logger.info(msg1)
self.assertRaisesErrno(zmq.EAGAIN, sub.recv, zmq.NOBLOCK)
topic,msg2 = sub2.recv_multipart()
self.assertEqual(topic, b'twoonly.INFO')
self.assertEqual(msg2, b(msg1)+b'\n')
logger.removeHandler(handler)
示例4: _transmit_one_msg_throughlistener
# 需要导入模块: import zmq [as 别名]
# 或者: from zmq import NOBLOCK [as 别名]
def _transmit_one_msg_throughlistener(self, msg, ident) -> Tuple[bool, Optional[str], bool]:
def prepare_error_msg(ex):
err_str = '{} got error {} while sending through listener to {}' \
.format(self, ex, ident)
print(err_str)
return err_str
need_to_resend = False
if isinstance(ident, str):
ident = ident.encode()
try:
msg = self._prepare_to_send(msg)
self.listener.send_multipart([ident, msg], flags=zmq.NOBLOCK)
except zmq.Again as ex:
need_to_resend = True
return False, prepare_error_msg(ex), need_to_resend
except zmq.ZMQError as ex:
need_to_resend = (ex.errno == 113)
return False, prepare_error_msg(ex), need_to_resend
except Exception as ex:
return False, prepare_error_msg(ex), need_to_resend
return True, None, need_to_resend
示例5: _receiveFromListener
# 需要导入模块: import zmq [as 别名]
# 或者: from zmq import NOBLOCK [as 别名]
def _receiveFromListener(self, quota: Quota) -> int:
"""
Receives messages from listener
:param quota: number of messages to receive
:return: number of received messages
"""
i = 0
incoming_size = 0
try:
ident, msg = self.listener.recv_multipart(flags=zmq.NOBLOCK)
if msg:
# Router probing sends empty message on connection
incoming_size += len(msg)
i += 1
self._verifyAndAppend(msg, ident)
except zmq.Again as e:
return i
except zmq.ZMQError as e:
print("Strange ZMQ behaviour during node-to-node message receiving, experienced {}".format(e))
if i > 0:
print('{} got {} messages through listener'.
format(self, i))
return i
示例6: transmit
# 需要导入模块: import zmq [as 别名]
# 或者: from zmq import NOBLOCK [as 别名]
def transmit(self, msg, uid, timeout=None, serialized=False, is_batch=False):
remote = self.remotes.get(uid)
err_str = None
if not remote:
return False, err_str
socket = remote.socket
if not socket:
return False, err_str
try:
if not serialized:
msg = self.prepare_to_send(msg)
print('{} transmitting message {} to {} by socket {} {}'
.format(self, msg, uid, socket.FD, socket.underlying))
socket.send(msg, flags=zmq.NOBLOCK)
return True, err_str
except zmq.Again:
print('{} could not transmit message to {}'.format(self, uid))
return False, err_str
示例7: poll_command_request
# 需要导入模块: import zmq [as 别名]
# 或者: from zmq import NOBLOCK [as 别名]
def poll_command_request(self):
"""If the command RPC socket has an incoming request,
separate it into its action and its params and put it
on the command request queue.
"""
try:
message = self.rpc.recv(zmq.NOBLOCK)
except zmq.ZMQError as exc:
if exc.errno == zmq.EAGAIN:
return
else:
raise
_logger.debug("Received command %s", message)
segments = _unpack(message)
action, params = segments[0], segments[1:]
_logger.debug("Adding %s, %s to the request queue", action, params)
self._command = _Command(action, params)
示例8: get_command
# 需要导入模块: import zmq [as 别名]
# 或者: from zmq import NOBLOCK [as 别名]
def get_command(self):
"""Attempt to return a unicode object from the command socket
If no message is available without blocking (as opposed to a blank
message), return None
"""
try:
message_bytes = self.socket.recv(zmq.NOBLOCK)
log.debug("Received message: %r", message_bytes)
except zmq.ZMQError as exc:
if exc.errno == zmq.EAGAIN:
return None
else:
raise
else:
return message_bytes.decode(config.CODEC)
示例9: _handle_recv
# 需要导入模块: import zmq [as 别名]
# 或者: from zmq import NOBLOCK [as 别名]
def _handle_recv(self):
"""Handle a recv event."""
if self._flushed:
return
try:
msg = self.socket.recv_multipart(zmq.NOBLOCK, copy=self._recv_copy)
except zmq.ZMQError as e:
if e.errno == zmq.EAGAIN:
# state changed since poll event
pass
else:
gen_log.error("RECV Error: %s"%zmq.strerror(e.errno))
else:
if self._recv_callback:
callback = self._recv_callback
# self._recv_callback = None
self._run_callback(callback, msg)
# self.update_state()
示例10: _abort_queue
# 需要导入模块: import zmq [as 别名]
# 或者: from zmq import NOBLOCK [as 别名]
def _abort_queue(self, stream):
poller = zmq.Poller()
poller.register(stream.socket, zmq.POLLIN)
while True:
idents,msg = self.session.recv(stream, zmq.NOBLOCK, content=True)
if msg is None:
return
self.log.info("Aborting:")
self.log.info("%s", msg)
msg_type = msg['header']['msg_type']
reply_type = msg_type.split('_')[0] + '_reply'
status = {'status' : 'aborted'}
md = {'engine' : self.ident}
md.update(status)
reply_msg = self.session.send(stream, reply_type, metadata=md,
content=status, parent=msg, ident=idents)
self.log.debug("%s", reply_msg)
# We need to wait a bit for requests to come in. This can probably
# be set shorter for true asynchronous clients.
poller.poll(50)
示例11: recv_array
# 需要导入模块: import zmq [as 别名]
# 或者: from zmq import NOBLOCK [as 别名]
def recv_array(socket, flags=0, copy=False, track=False, block=True):
"""recv a numpy array"""
if block:
md = socket.recv_json(flags=flags)
msg = socket.recv(flags=flags, copy=copy, track=track)
buf = bytearray(msg)
A = np.frombuffer(buf, dtype=md['dtype'])
return A.reshape(md['shape'])
else:
try:
md = socket.recv_json(flags=flags | zmq.NOBLOCK)
msg = socket.recv(flags=flags | zmq.NOBLOCK, copy=copy, track=track)
buf = bytearray(msg)
A = np.frombuffer(buf, dtype=md['dtype'])
return A.reshape(md['shape'])
except zmq.Again:
return False
示例12: receive
# 需要导入模块: import zmq [as 别名]
# 或者: from zmq import NOBLOCK [as 别名]
def receive(self, timeout=30):
"""
Try to send the message until it either has been received or
hits timeout.
:param timeout: Timeout to retry receiving the message
:type timeout: ``int``
:return: The received message
:rtype: ``object`` or ``str`` or ``zmq.sugar.frame.Frame``
"""
return retry_until_timeout(
exception=zmq.ZMQError,
item=self._socket.recv,
kwargs={"flags": zmq.NOBLOCK},
timeout=timeout,
raise_on_timeout=True,
)
示例13: send
# 需要导入模块: import zmq [as 别名]
# 或者: from zmq import NOBLOCK [as 别名]
def send(self, data, timeout=30):
"""
Try to send the message until it either sends or hits timeout.
:param data: The content of the message.
:type data: ``bytes`` or ``zmq.sugar.frame.Frame`` or ``memoryview``
:param timeout: Timeout to retry sending the message.
:type timeout: ``int``
:return: ``None``
:rtype: ``NoneType``
"""
return retry_until_timeout(
exception=zmq.ZMQError,
item=self._socket.send,
kwargs={"data": data, "flags": zmq.NOBLOCK},
timeout=timeout,
raise_on_timeout=True,
)
示例14: receive
# 需要导入模块: import zmq [as 别名]
# 或者: from zmq import NOBLOCK [as 别名]
def receive(self, timeout=30):
"""
Try to receive the message until it has either been received or
hits timeout.
:param timeout: Timeout to retry receiving the message.
:type timeout: ``int``
:return: The received message.
:rtype: ``bytes`` or ``zmq.sugar.frame.Frame`` or ``memoryview``
"""
return retry_until_timeout(
exception=zmq.ZMQError,
item=self._socket.recv,
kwargs={"flags": zmq.NOBLOCK},
timeout=timeout,
raise_on_timeout=True,
)
示例15: generator_from_zmq_pull
# 需要导入模块: import zmq [as 别名]
# 或者: from zmq import NOBLOCK [as 别名]
def generator_from_zmq_pull(context, host):
socket = context.socket(zmq.PULL)
# TODO: Configure socket with clean properties to avoid message overload.
if host.endswith('/'):
host = host[:-1]
print_item("+", "Binding ZMQ pull socket : " + colorama.Fore.CYAN + "{0}".format(host) + colorama.Style.RESET_ALL)
socket.bind(host)
while True:
try:
message = socket.recv(flags=zmq.NOBLOCK)
except zmq.Again as e:
message = None
if message is None:
yield None # NOTE: We have to make the generator non blocking.
else:
task = json.loads(message)
yield task