Skip to content

Instantly share code, notes, and snippets.

@devos50
Created June 19, 2016 20:45
Show Gist options
  • Save devos50/74d1e1ec43a069abfee34e98f95a0a68 to your computer and use it in GitHub Desktop.
Save devos50/74d1e1ec43a069abfee34e98f95a0a68 to your computer and use it in GitHub Desktop.
@inlineCallbacks
def receive_packet(self, addresses=None, timeout=0.5):
"""
Returns the first matching (candidate, packet) tuple from incoming UDP packets.
ADDRESSES must be None or a list of address tuples. When it is a list of addresses, only
UDP packets from ADDRESSES will be returned.
"""
assert addresses is None or isinstance(addresses, list)
assert addresses is None or all(isinstance(address, tuple) for address in addresses)
assert isinstance(timeout, (int, float)), type(timeout)
timeout = time() + timeout
while timeout > time():
packets = self._dispersy.endpoint.clear_receive_queue()
if packets:
return_list = []
for address, packet in packets:
if not (addresses is None or address in addresses or (address[0] == "127.0.0.1" and ("0.0.0.0", address[1]) in addresses)):
self._logger.debug("Ignored %d bytes from %s:%d", len(packet), address[0], address[1])
continue
if packet.startswith("ffffffff".decode("HEX")):
tunnel = True
packet = packet[4:]
else:
tunnel = False
candidate = Candidate(address, tunnel)
self._logger.debug("%d bytes from %s", len(packet), candidate)
return_list.append((candidate, packet))
returnValue(iter(return_list))
else:
yield deferLater(reactor, 0.001, lambda: None)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment