本文整理汇总了Python中zmq.Socket方法的典型用法代码示例。如果您正苦于以下问题:Python zmq.Socket方法的具体用法?Python zmq.Socket怎么用?Python zmq.Socket使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类zmq
的用法示例。
在下文中一共展示了zmq.Socket方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: poll
# 需要导入模块: import zmq [as 别名]
# 或者: from zmq import Socket [as 别名]
def poll(self, timeout=None):
"""Poll the registered 0MQ or native fds for I/O.
Parameters
----------
timeout : float, int
The timeout in milliseconds. If None, no `timeout` (infinite). This
is in milliseconds to be compatible with ``select.poll()``.
Returns
-------
events : list of tuples
The list of events that are ready to be processed.
This is a list of tuples of the form ``(socket, event)``, where the 0MQ Socket
or integer fd is the first element, and the poll event mask (POLLIN, POLLOUT) is the second.
It is common to call ``events = dict(poller.poll())``,
which turns the list of tuples into a mapping of ``socket : event``.
"""
if timeout is None or timeout < 0:
timeout = -1
elif isinstance(timeout, float):
timeout = int(timeout)
return zmq_poll(self.sockets, timeout=timeout)
示例2: __init__
# 需要导入模块: import zmq [as 别名]
# 或者: from zmq import Socket [as 别名]
def __init__(self, context=None, socket_type=-1, io_loop=None, **kwargs):
if isinstance(context, _zmq.Socket):
context, from_socket = (None, context)
else:
from_socket = kwargs.pop('_from_socket', None)
if from_socket is not None:
super(_AsyncSocket, self).__init__(shadow=from_socket.underlying)
self._shadow_sock = from_socket
else:
super(_AsyncSocket, self).__init__(context, socket_type, **kwargs)
self._shadow_sock = _zmq.Socket.shadow(self.underlying)
self.io_loop = io_loop or self._default_loop()
self._recv_futures = deque()
self._send_futures = deque()
self._state = 0
self._fd = self._shadow_sock.FD
self._init_io_state()
示例3: test_shadow_pyczmq
# 需要导入模块: import zmq [as 别名]
# 或者: from zmq import Socket [as 别名]
def test_shadow_pyczmq(self):
try:
from pyczmq import zctx, zsocket
except Exception:
raise SkipTest("Requires pyczmq")
ctx = zctx.new()
ca = zsocket.new(ctx, zmq.PUSH)
cb = zsocket.new(ctx, zmq.PULL)
a = zmq.Socket.shadow(ca)
b = zmq.Socket.shadow(cb)
a.bind("inproc://a")
b.connect("inproc://a")
a.send(b'hi')
rcvd = self.recv(b)
self.assertEqual(rcvd, b'hi')
示例4: test_skt_reinit
# 需要导入模块: import zmq [as 别名]
# 或者: from zmq import Socket [as 别名]
def test_skt_reinit():
result = {'foo': None, 'bar': None}
@socket(zmq.PUB)
def f(key, skt):
assert isinstance(skt, zmq.Socket), skt
result[key] = skt
foo_t = threading.Thread(target=f, args=('foo',))
bar_t = threading.Thread(target=f, args=('bar',))
foo_t.start()
bar_t.start()
foo_t.join()
bar_t.join()
assert result['foo'] is not None, result
assert result['bar'] is not None, result
assert result['foo'] is not result['bar'], result
示例5: test_multi_skts
# 需要导入模块: import zmq [as 别名]
# 或者: from zmq import Socket [as 别名]
def test_multi_skts():
@socket(zmq.PUB)
@socket(zmq.SUB)
@socket(zmq.PUSH)
def test(pub, sub, push):
assert isinstance(pub, zmq.Socket), pub
assert isinstance(sub, zmq.Socket), sub
assert isinstance(push, zmq.Socket), push
assert pub.context is zmq.Context.instance()
assert sub.context is zmq.Context.instance()
assert push.context is zmq.Context.instance()
assert pub.type == zmq.PUB
assert sub.type == zmq.SUB
assert push.type == zmq.PUSH
test()
示例6: test_multi_skts_with_name
# 需要导入模块: import zmq [as 别名]
# 或者: from zmq import Socket [as 别名]
def test_multi_skts_with_name():
@socket('foo', zmq.PUSH)
@socket('bar', zmq.SUB)
@socket('baz', zmq.PUB)
def test(foo, bar, baz):
assert isinstance(foo, zmq.Socket), foo
assert isinstance(bar, zmq.Socket), bar
assert isinstance(baz, zmq.Socket), baz
assert foo.context is zmq.Context.instance()
assert bar.context is zmq.Context.instance()
assert baz.context is zmq.Context.instance()
assert foo.type == zmq.PUSH
assert bar.type == zmq.SUB
assert baz.type == zmq.PUB
test()
示例7: test_skt_multi_thread
# 需要导入模块: import zmq [as 别名]
# 或者: from zmq import Socket [as 别名]
def test_skt_multi_thread():
@socket(zmq.PUB)
@socket(zmq.SUB)
@socket(zmq.PUSH)
def f(pub, sub, push):
assert isinstance(pub, zmq.Socket), pub
assert isinstance(sub, zmq.Socket), sub
assert isinstance(push, zmq.Socket), push
assert pub.context is zmq.Context.instance()
assert sub.context is zmq.Context.instance()
assert push.context is zmq.Context.instance()
assert pub.type == zmq.PUB
assert sub.type == zmq.SUB
assert push.type == zmq.PUSH
assert len(set(map(id, [pub, sub, push]))) == 3
threads = [threading.Thread(target=f) for i in range(8)]
[t.start() for t in threads]
[t.join() for t in threads]
示例8: multi_skts_method_other_args
# 需要导入模块: import zmq [as 别名]
# 或者: from zmq import Socket [as 别名]
def multi_skts_method_other_args(self):
@socket(zmq.PUB)
@socket(zmq.SUB)
def f(foo, pub, sub, bar=None):
assert isinstance(pub, zmq.Socket), pub
assert isinstance(sub, zmq.Socket), sub
assert foo == 'mock'
assert bar == 'fake'
assert pub.context is zmq.Context.instance()
assert sub.context is zmq.Context.instance()
assert pub.type is zmq.PUB
assert sub.type is zmq.SUB
f('mock', bar='fake')
示例9: poll
# 需要导入模块: import zmq [as 别名]
# 或者: from zmq import Socket [as 别名]
def poll(self, timeout=None):
"""Poll the registered 0MQ or native fds for I/O.
Parameters
----------
timeout : float, int
The timeout in milliseconds. If None, no `timeout` (infinite). This
is in milliseconds to be compatible with ``select.poll()``. The
underlying zmq_poll uses microseconds and we convert to that in
this function.
Returns
-------
events : list of tuples
The list of events that are ready to be processed.
This is a list of tuples of the form ``(socket, event)``, where the 0MQ Socket
or integer fd is the first element, and the poll event mask (POLLIN, POLLOUT) is the second.
It is common to call ``events = dict(poller.poll())``,
which turns the list of tuples into a mapping of ``socket : event``.
"""
if timeout is None or timeout < 0:
timeout = -1
elif isinstance(timeout, float):
timeout = int(timeout)
return zmq_poll(self.sockets, timeout=timeout)
示例10: _set_handler
# 需要导入模块: import zmq [as 别名]
# 或者: from zmq import Socket [as 别名]
def _set_handler(self, socket, handler, update=False):
"""
Set the socket handler(s).
Parameters
----------
socket : zmq.Socket
Socket to set its handler(s).
handler : function(s)
Handler(s) for the socket. This can be a list or a dictionary too.
"""
if update:
try:
self._handler[socket].update(self._curated_handlers(handler))
except KeyError:
self._handler[socket] = self._curated_handlers(handler)
else:
self._handler[socket] = self._curated_handlers(handler)
示例11: _process_single_event
# 需要导入模块: import zmq [as 别名]
# 或者: from zmq import Socket [as 别名]
def _process_single_event(self, socket):
"""
Process a socket's event.
Parameters
----------
socket : zmq.Socket
Socket that generated the event.
"""
data = socket.recv()
address = self._address[socket]
if address.kind == 'SUB':
self._process_sub_event(socket, address, data)
elif address.kind == 'PULL':
self._process_pull_event(socket, address, data)
elif address.kind == 'REP':
self._process_rep_event(socket, address, data)
else:
self._process_single_event_complex(address, socket, data)
示例12: _process_rep_event
# 需要导入模块: import zmq [as 别名]
# 或者: from zmq import Socket [as 别名]
def _process_rep_event(self, socket, addr, data):
"""
Process a REP socket's event.
Parameters
----------
socket : zmq.Socket
Socket that generated the event.
addr : AgentAddress
AgentAddress associated with the socket that generated the event.
data : bytes
Data received on the socket.
"""
message = deserialize_message(message=data, serializer=addr.serializer)
handler = self._handler[socket]
if inspect.isgeneratorfunction(handler):
generator = handler(self, message)
socket.send(serialize_message(next(generator), addr.serializer))
execute_code_after_yield(generator)
else:
reply = handler(self, message)
socket.send(serialize_message(reply, addr.serializer))
示例13: _process_pull_event
# 需要导入模块: import zmq [as 别名]
# 或者: from zmq import Socket [as 别名]
def _process_pull_event(self, socket, addr, data):
"""
Process a PULL socket's event.
Parameters
----------
socket : zmq.Socket
Socket that generated the event.
addr : AgentAddress
AgentAddress associated with the socket that generated the event.
data : bytes
Data received on the socket.
"""
message = deserialize_message(message=data, serializer=addr.serializer)
handler = self._handler[socket]
if not isinstance(handler, (list, dict, tuple)):
handler = [handler]
for h in handler:
h(self, message)
示例14: _create_socket
# 需要导入模块: import zmq [as 别名]
# 或者: from zmq import Socket [as 别名]
def _create_socket(self, socket_type, linger_value):
"""
Create a socket of the given type, bind it to a random port and
register it to the poller
:param int socket_type: type of the socket to open
:param int linger_value: -1 mean wait for receive all msg and block
closing 0 mean hardkill the socket even if msg
are still here.
:return (zmq.Socket, int): the initialized socket and the port where the
socket is bound
"""
socket = SafeContext.get_context().socket(socket_type)
socket.setsockopt(zmq.LINGER, linger_value)
socket.set_hwm(0)
port_number = socket.bind_to_random_port(LOCAL_ADDR)
self.poller.register(socket, zmq.POLLIN)
self.logger.debug("bind to " + LOCAL_ADDR + ':' + str(port_number))
return (socket, port_number)
示例15: _recv_ack
# 需要导入模块: import zmq [as 别名]
# 或者: from zmq import Socket [as 别名]
def _recv_ack(sub_channel: Socket, topic: str, expected_content: bool = True):
""" Blocks until an acknowledge-message for the specified topic with the expected content is received via the
specified subscriber channel.
Args:
sub_channel (Socket): subscriber socket
topic (str): topic to listen for ACK's
expected_content (bool): are we expecting `True` (ACK) or `False` (NACK)
"""
ack_topic = topic if topic.startswith("ACK/") else f"ACK/{topic}"
while True:
msg = sub_channel.recv_multipart(copy=True)
recv_topic = msg[0].decode("ascii")
content = pickle.loads(msg[1])[1] # pickle.loads(msg) -> tuple(timestamp, content) -> return content
if recv_topic == ack_topic:
if content == expected_content:
return