Fhernd icon

soporte_gestion_contexto.py

Fhernd | PRO | 12/06/18 01:23:14 AM UTC | 0 ⭐ | 2871 👁️ | Never ⏰ | []
Python |

1.08 KB

|

None

|

0 👍

/

0 👎

from socket import socket, AF_INET, SOCK_STREAM
from functools import partial
 
class ConexionDiferida:
    def __init__(self, direccion, familia=AF_INET, tipo=SOCK_STREAM):
        self.direccion = direccion
        self.familia = AF_INET
        self.tipo = SOCK_STREAM
        self.sock = None
 
    def __enter__(self):
        if self.sock is not None:
            raise Runtimeerror('La conexión ya se ha realizado')
 
        self.sock = socket(self.familia, self.tipo)
        self.sock.connect(self.direccion)
 
        return self.sock
 
    def __exit__(self, exc_type, exc_val, exc_tb):
        self.sock.close()
        self.sock = None
 
 
if __name__ == '__main__':
    conexion = ConexionDiferida(('www.python.org', 80))
 
    with conexion as s:
        # conexion.__enter__() se ejecuta: la conexión se abre
 
        s.send(b'GET /index.html HTTP/1.0\r\n')
        s.send(b'Host: www.python.org\r\n')
        s.send(b'\r\n')
 
        respuesta = b''.join(iter(partial(s.recv, 8192), b''))
 
        # conexion.__exit__() se ejecuta: la conexión se cierra

Comments

  •  icon
    01/01/70 12:00:00 AM UTC
    Plain Text |

    0 B

    |

    👍

    /

    👎