Skip to content

Instantly share code, notes, and snippets.

View openalmeida's full-sized avatar

Hugo Almeida openalmeida

  • Chendu, Sichuan, PRC
View GitHub Profile
@geertj
geertj / winsocketpair.py
Last active April 12, 2021 08:13
Emulates the UNIX socketpair() system call on Windows. This function uses a trick with non-blocking sockets to prevent the need for a thread. A socketpair can be used as a full-duplex, select()able pipe on Windows.
def socketpair(family=socket.AF_INET, type=socket.SOCK_STREAM, proto=0):
"""Emulate the Unix socketpair() function on Windows."""
# We create a connected TCP socket. Note the trick with setblocking(0)
# that prevents us from having to create a thread.
lsock = socket.socket(family, type, proto)
lsock.bind(('localhost', 0))
lsock.listen(1)
addr, port = lsock.getsockname()
csock = socket.socket(family, type, proto)
csock.setblocking(0)