Skip to content

Instantly share code, notes, and snippets.

@Fhernd
Created December 6, 2018 02:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Fhernd/02d34dcd2a6e7b20eea17a7715a1a9a6 to your computer and use it in GitHub Desktop.
Save Fhernd/02d34dcd2a6e7b20eea17a7715a1a9a6 to your computer and use it in GitHub Desktop.
Uso del protocolo de autogestión para una clase de conexión diferida.
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment