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?
1 Answer 1
You're pressing Ctrl-C on the client side. This causes the server's self.channel to 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:
data = self.channel.recv ( 1024 )
if not data: break # <<< ADD THIS
Or, as suggested by @sr2222, you can combine both this and your current check into one:
if not data or 'exit' in data:
This will exit the loop if the channel has been closed.
4 Comments
if not data or 'exit' in data:'exit' in data check sends data back over the connection, which will not be valid if data is empty.send() on a closed channel is a no-op. However, some might question this approach on stylistic grounds.
if 'exit' in data:. If this is a chat server, this means no one can ever send a message containing the word 'exit' unless they manage to make it span across 2 buffer-sized data blocks.if data == 'exit':will probably work more as you'd like.