[Python] Prevent reading data from a closed TCP socket

Discussão em 'Python' iniciado por Stack, Junho 5, 2025.

  1. Stack

    Stack Membro Participativo

    In my application, a client and a server communicate over a TCP socket using a request-reply protocol. Sometimes, because of network issues or application issues, the socket read on the server side is delayed by seconds, during which the client might have closed the TCP connection.

    In that case, when the server eventually reads from the socket, I would like the server to discard all the pending data on the socket and immediately close the socket, since the client has already closed the connection and processing the data would be throw away work.

    Here is a minimal reproducible example in Python:

    Client:

    import socket, time

    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
    s.connect(("my_host", 56566))

    s.sendall(b"Hello, world")

    s.close()


    Server:

    import socket, time

    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
    s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

    s.bind(("0.0.0.0", 56566))
    s.listen()

    conn, addr = s.accept()

    # Delay socket read
    time.sleep(5)

    data = conn.recv(1024)
    print("Received bytes: " + str(data)) # <-- "Hello, world" is read
    data = conn.recv(1024)
    print("Received bytes: " + str(data)) # <-- "" is read, indicating socket close


    How can I detect that the socket has been closed and discard pending data during the read ? I have tried using SO_LINGER and socket shutdown without success.

    Continue reading...

Compartilhe esta Página