I am creating a chat server in python and got quite far as a noob in the language. I am having 1 problem at the moment which I want to solve before I go further, but I cannot seem to find how to get the problem solved.
It is about a while loop that continues..
in the below code is where it goes wrong
while 1:
try:
data = self.channel.recv ( 1024 )
print "Message from client: ", data
if "exit" in data:
self.channel.send("You have closed youre connection.\n")
break
except KeyboardInterrupt:
break
except:
raise
When this piece of code get executed, on my client I need to enter “exit” to quit the connection. This works as a charm, but when I use CTRL+C to exit the connection, my server prints “Message from client: ” a couple of thousand times.
where am I going wrong?
You’re pressing Ctrl-C on the client side. This causes the server’s
self.channelto get closed.Since calling
recv()on a closed channel immediately returns a blank string, your server code gets stuck in an infinite loop.To fix this, add the following line to your server code:
Or, as suggested by @sr2222, you can combine both this and your current check into one:
This will exit the loop if the channel has been closed.