Since what you send through the sockets are bytes (without coding), the comparison if recibido == "quit":
will never be True
. Since "quit" != b"quit"
. You should compare with:
if recibido == b"quit":
or decode the string of bytes that reaches UTF-8:
while True:
print ("Esperando conexión...")
sc, addr = s.accept()
print ("Cliente conectado desde: ", addr)
while True:
recibido = sc.recv(1024)
msg = recibido.decode("UTF-8") # <<<<<<<<
if msg == "quit":
print("El cliente {} se desconectó.".format(addr))
break
print ("Recibido: ", msg)
Some notes regarding the client:
-
It has the wrong port, it must be 9999 (according to the server) and you have 999.
-
In Python 3 input
already returns a string, the casting to str
is not necessary (and in Python 2 you should not use input
for this ever , for that's raw_input
).
-
You should add another conditional on the client to also exit when "quit" is sent.
It might look something like this:
import socket
socket_cliente = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket_cliente.connect(("localhost", 9999))
while True:
mensaje = input(">> ")
socket_cliente.send(mensaje.encode('utf-8'))
if mensaje == "quit":
break
recibido = socket_cliente.recv(1024)
print("Recibido: ", recibido)
print ("Adios")
socket_cliente.close()
Edit:
If you want the server to close also when the client sends the "quit" signal then you must also break the cycle in charge of waiting and accepting the clients. Since break
only breaks the cycle where it is nested, you can use a control variable instead:
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(("127.0.0.1", 9999))
s.listen(1)
print ("Servidor de Chat\n")
run = True
while run:
print ("Esperando conexión...")
sc, addr = s.accept()
print ("Cliente conectado desde: ", addr)
while run:
recibido = sc.recv(1024)
msg = recibido.decode("UTF-8")
if msg == "quit":
print("El cliente {} se desconectó.".format(addr))
run = False
print ("Recibido: ", msg)
nuestra_respuesta = "Hola cliente, yo soy el servidor."
sc.send(nuestra_respuesta.encode('utf-8'))
print ("Adios")
s.close()
But since, as is logical, you are only going to accept a client in this case, the first while
simply exceeds:
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(("127.0.0.1", 9999))
s.listen(1)
print ("Servidor de Chat\n")
print ("Esperando conexión...")
sc, addr = s.accept()
print ("Cliente conectado desde: ", addr)
while True:
recibido = sc.recv(1024)
msg = recibido.decode("UTF-8")
if msg == "quit":
print("El cliente {} se desconectó.".format(addr))
break
print ("Recibido: ", msg)
nuestra_respuesta = "Hola cliente, yo soy el servidor."
sc.send(nuestra_respuesta.encode('utf-8'))
print ("Adios")
s.close()