pythonsocketspython-asyncio

What is the difference between `asyncio.open_connection` and `socket.socket.accept()`


I'm trying to connect to a server. Our client-side script opens the connection using:

reader, writer = await asyncio.open_connection(HOST, PORT)

We wanted to integrate this with legacy code that opens a connection using:

with socket.socket(socket.AF_INET,socket.SOCK_STREAM) as s:
    s.bind((HOST,PORT))
    s.listen()
    conn, addr = s.accept()
    print("Accepted")

But then s.accept() hangs forever and connection is not established.

Is there any reason why asyncio.open_connection(HOST, PORT) would work while socket.socket.accept() fails?


Solution

  • What is the difference between asyncio.open_connection and socket.socket.accept()?

    These functions have nothing in common and are used for opposite purposes:

    So, open_connection is not a replacement for accept — this would be socket.connect instead. Similarly, accept is not a replacement for open_connection — this would be asyncio.start_server instead.