1. from socket import socket, AF_INET, SOCK_STREAM
    2. class LazyConnection:
    3. def __init__(self, address, family=AF_INET, type=SOCK_STREAM):
    4. self.address = address
    5. self.family = family
    6. self.type = type
    7. self.connections = []
    8. def __enter__(self):
    9. sock = socket(self.family, self.type)
    10. sock.connect(self.address)
    11. self.connections.append(sock)
    12. return sock
    13. def __exit__(self, exc_type, exc_val, exc_tb):
    14. self.connections.pop().close()
    15. if __name__ == '__main__':
    16. from functools import partial
    17. conn = LazyConnection(('www.python.org', 80))
    18. with conn as s1:
    19. pass
    20. with conn as s2:
    21. s1.send(b'GET /index.html HTTP/1.0\r\n')
    22. s1.send(b'Host: www.python.org\r\n')
    23. s1.send(b'\r\n')
    24. resp = b''.join(iter(partial(s1.recv, 8192), b''))
    25. print(resp.decode())