El cliente es la otra mitad del sistema. Si el servidor responde con OK tamaño, el cliente sabe cuántos bytes debe leer para completar la descarga.
1) Conexión y envío de comando
import socket
HOST = "127.0.0.1"
PORT = 5000
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as c:
c.connect((HOST, PORT))
c.sendall(b"GET ejemplo.txt\n")
# ... leer respuesta ...
2) Leer cabecera y contenido
Leemos hasta \n para obtener la cabecera. Después leemos exactamente tamaño bytes.
def recv_line(sock):
buf = b""
while b"\n" not in buf:
chunk = sock.recv(1)
if not chunk:
break
buf += chunk
return buf.decode("utf-8", errors="ignore").strip()
header = recv_line(c)
if header.startswith("OK "):
size = int(header.split(" ", 1)[1])
data = b""
while len(data) < size:
data += c.recv(min(4096, size - len(data)))
open("descargado.txt", "wb").write(data)
else:
print("Error:", header)
3) Cerrar sesión
c.sendall(b"END\n")
print(recv_line(c)) # BYE