break does not break the client listening cycle on server when receiving keyword

1

I have two codes: one the server and the other the client:

The server:

import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

s.bind(("127.0.0.1", 9999))

s.listen(5)

print ("Servidor de Chat\n")


while True:

        print ("Esperando conexión...")
        sc, addr = s.accept()
        print ("Cliente conectado desde: ", addr)

        while True:
                recibido = sc.recv(1024)
                if recibido == "quit":
                        break
                print ("Recibido: ", recibido)

                nuestra_respuesta = "Hola cliente, yo soy el servidor."
                sc.send(nuestra_respuesta.encode('utf-8'))

print ("Adios")

sc.close()

s.close()

The customer:

import socket

socket_cliente = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket_cliente.connect(("127.0.0.1", 999))

while True:
    mensaje = str(input(">> "))
    socket_cliente.send(mensaje.encode('utf-8'))

    recibido = socket_cliente.recv(1024)
    print("Recibido: ", recibido)

print ("Adios")

socket_cliente.close()

The problem is on the server, on line 12:

if recibido == "quit":
    break

By putting "quit" on the client does not break the server loop and continues its execution. The break is not working.

Credits to Barlan

    
asked by telegrima 16.12.2017 в 20:23
source

1 answer

1

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()
    
answered by 16.12.2017 в 21:01