import socket
import threading

def main():
    errors = []
    with socket.socket() as listener:
        listener.bind(("127.0.0.1", 0))
        listener.listen(1)
        listener.settimeout(2)
        def peer():
            try:
                with listener.accept()[0] as conn:
                    conn.settimeout(2)
                    data = bytearray()
                    while chunk := conn.recv(32):
                        data.extend(chunk)
                    assert data == b"Q001"
                    print("服务端收到请求后EOF")
                    conn.sendall(b"ACK")
            except BaseException as e:
                errors.append(e)
        thread = threading.Thread(target=peer)
        thread.start()
        try:
            with socket.create_connection(listener.getsockname(), 2) as client:
                client.sendall(b"Q001")
                client.shutdown(socket.SHUT_WR)
                data = bytearray()
                while chunk := client.recv(32):
                    data.extend(chunk)
                assert data == b"ACK"
                print("客户端仍收到 ACK")
        finally:
            thread.join(3)
        assert not thread.is_alive() and not errors, errors
    a,b = socket.socketpair()
    try:
        a.settimeout(0.02)
        try:
            a.recv(1)
            raise AssertionError("应超时")
        except TimeoutError:
            print("超时测试通过")
    finally:
        a.close()
        b.close()

if __name__ == "__main__":
    main()
