user237252
user237252

Reputation: 63

Infinite Loop Error while Running Chatroom in Terminal using Python

I have implemented a simple chatroom using python. When the users exits (closes the terminal window) the program breaks and show an endless loop of a message. I have the following code to treat exception (when no message is received) but, it doesn't go into that and doesn't close the client socket connection. Any help would be highly appreciated on how shall I close the client socket after it disconnects? Thanks!

def handle(client):
    while True:
        try:
            message = client.recv(1024)
            messages = message.decode('ascii')
            index = clients.index(client)
            clientname = clientnames[index]
            print("<{}> {}".format(clientname, messages))
            broadcast("({}) {}".format(clientname, messages).encode('ascii'), index)
        except:
            index = clients.index(client)
            clientname = clientnames[index]
            print("{} left!".format(clientname))
            broadcast('{} left!'.format(clientname).encode('ascii'), index)
            clientnames.remove(clientname)
            clients.remove(client)
            client.close()
            break

Upvotes: 0

Views: 54

Answers (1)

Alexander Riedel
Alexander Riedel

Reputation: 1359

According my comments, giving you this piece of code. I don't if its working right away, because I have not seen the other methods you implemented yet. Especially, check if messages is a list or something as the name implies and change accordingly.

Function: If you send quit to the bot, everything will be closed

def handle(client):
    while True:
        try:
            message = client.recv(1024)
            messages = message.decode('ascii')
            if messages == "quit":
                print("{} left!".format(clientname))
                broadcast('{} left!'.format(clientname).encode('ascii'), index)
                clientnames.remove(clientname)
                clients.remove(client)
                client.close()
                break
            index = clients.index(client)
            clientname = clientnames[index]
            print("<{}> {}".format(clientname, messages))
            broadcast("({}) {}".format(clientname, messages).encode('ascii'), index)
        except:
            print("Error on receiving")

Upvotes: 1

Related Questions