简体   繁体   English

卡在循环python中

[英]stuck in while loop python

I am creating a chat server in python and got quite far as a noob in the language. 我正在python中创建一个聊天服务器,并且在语言中得到了很高的菜鸟。 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. 当这段代码被执行时,在我的客户端上我需要输入“exit”来退出连接。 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. 这可以作为一个魅力,但当我使用CTRL + C退出连接时,我的服务器打印“来自客户端的消息:”几千次。

where am I going wrong? 我哪里错了?

You're pressing Ctrl-C on the client side. 你在客户端按Ctrl-C。 This causes the server's self.channel to get closed. 这会导致服务器的self.channel关闭。

Since calling recv() on a closed channel immediately returns a blank string, your server code gets stuck in an infinite loop. 由于在封闭通道上调用recv()立即返回一个空字符串,因此您的服务器代码会陷入无限循环。

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: 或者,正如@ sr2222所建议的那样,您可以将这个和当前的检查合并为一个:

if not data or 'exit' in data: 

This will exit the loop if the channel has been closed. 如果通道已关闭,这将退出循环。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM