Skip to content

Instantly share code, notes, and snippets.

@davidkhess
Last active February 21, 2019 14:33
Show Gist options
  • Save davidkhess/bc213e643db2581ee830a1e706e85f8f to your computer and use it in GitHub Desktop.
Save davidkhess/bc213e643db2581ee830a1e706e85f8f to your computer and use it in GitHub Desktop.
Happy Eyeballs solution using gevent modeled after Nathaniel J. Smith's canonical version for Trio
import gevent
import gevent.event
import gevent.socket
import gevent.pool
def open_tcp_socket(hostname, port, *, timeout=0.250):
targets = gevent.socket.getaddrinfo(hostname, port, type=gevent.socket.SOCK_STREAM)
result = gevent.event.AsyncResult()
group = gevent.pool.Group()
def attempt(target):
*socket_config, _, socket_target = target
socket = gevent.socket.socket(*socket_config)
socket.connect(socket_target)
result.set(socket)
group.kill()
for target in targets:
group.spawn(attempt, target)
result.wait(timeout=timeout)
if result.ready():
break
try:
return result.get()
except:
raise OSError("failed")
print(open_tcp_socket("debian.org", "https"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment