23.11.2012 Views

Python para todos

Python para todos

Python para todos

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

<strong>Python</strong> <strong>para</strong> <strong>todos</strong><br />

Una vez que hemos terminado de trabajar con el socket, lo cerramos<br />

con el método close.<br />

Crear un cliente es aún más sencillo. Solo tenemos que crear el objeto<br />

socket, utilizar el método connect <strong>para</strong> conectarnos al servidor y utilizar<br />

los mé<strong>todos</strong> send y recv que vimos anteriormente. El argumento<br />

de connect es una tupla con host y puerto, exactamente igual que bind.<br />

socket_c = socket.socket()<br />

socket_c.connect((“localhost”, 9999))<br />

socket_c.send(“hola”)<br />

Veamos por último un ejemplo completo. En este ejemplo el cliente<br />

manda al servidor cualquier mensaje que escriba el usuario y el servidor<br />

no hace más que repetir el mensaje recibido. La ejecución termina<br />

cuando el usuario escribe quit.<br />

Este sería el código del script servidor:<br />

import socket<br />

s = socket.socket()<br />

s.bind((“localhost”, 9999))<br />

s.listen(1)<br />

sc, addr = s.accept()<br />

while True:<br />

recibido = sc.recv(1024)<br />

if recibido == “quit”:<br />

break<br />

print “Recibido:”, recibido<br />

sc.send(recibido)<br />

print “adios”<br />

sc.close()<br />

s.close()<br />

Y a continuación tenemos el del script cliente:<br />

import socket<br />

s = socket.socket()<br />

s.connect((“localhost”, 9999))<br />

94

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!