Created
July 1, 2018 02:09
-
-
Save cqfd/d6577fb5ce69aeaca96efce7ae5369bd to your computer and use it in GitHub Desktop.
Happy eyeballs in Trio
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import trio | |
async def open_tcp_socket(host_name, port, patience_in_seconds=1): | |
targets = await trio.socket.getaddrinfo( | |
host_name, port, type=trio.socket.SOCK_STREAM | |
) | |
winning_socket = None | |
async with trio.open_nursery() as nursery: | |
for *socket_config, _, target in targets: | |
attempt_failed = trio.Event() | |
async def attempt_to_connect(socket_config): | |
try: | |
socket = trio.socket.socket(*socket_config) | |
await socket.connect(target) | |
except OSError: | |
attempt_failed.set() | |
else: | |
nonlocal winning_socket | |
winning_socket = socket | |
nursery.cancel_scope.cancel() | |
nursery.start_soon(attempt_to_connect, socket_config) | |
with trio.move_on_after(patience_in_seconds): | |
await attempt_failed.wait() | |
if winning_socket is None: | |
raise OSError("shoot") | |
else: | |
return winning_socket |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment