套接字输入卡在循环中



我正在处理这段代码,我成功地从套接字接收到了一个输入,但如果输入了错误的输入,它就会中断并在测试循环中保持循环。我希望它等待另一个输入,但有什么东西导致它循环。有人能帮我弄清楚挂在这个环上的是什么吗?

接收插座的代码。

data = conn.recv(2042)  
line=data.decode('UTF-8')
continue_q=line
#print (continue_q)
while True:
if continue_q !=  "y" or "Y" or "n" or "N":
print("atgorboge")
#continue_q = input("Please address errors. " 
#                   "Continue? (Y/N) ")
print("please adress errors. continue? (Y/N)")

#continue_q=None
#while True:
time.sleep(5)

data = conn.recv(2042)  
line=data.decode('UTF-8')
print(continue_q)
continue_q=line

#redirectOut()
if( (continue_q == 'y') or (continue_q == 'Y') ):
print('poped to yes')
clear_json_flags(DEBUG_PRINT, WC)
update_json_file(DEBUG_PRINT, CONFIG_FILE, WC)
#redirectOut()
return 0
if( (continue_q == 'n') or (continue_q == 'N') ):
print('poped to no')
return -1
#redirectOut()

输出:

Please address errors. Continue? (Y/N)
Socket created
None
Socket bind complete
Socket now listening
Connected to 192.168.0.11:50183
atgorboge
please adress errors. continue? (Y/N)
l
atgorboge
please adress errors. continue? (Y/N)
atgorboge
please adress errors. continue? (Y/N)
atgorboge
please adress errors. continue? (Y/N)

这根本不是套接字或循环特有的。

if continue_q != "y" or "Y" or "n" or "N":总是计算为True,因为它被计算为if (continue_q != "y") or ("Y")...并且"Y"是True。

你会想要例如

if continue_q not in ("y", "Y", "n", "N"):

除此之外,像那样天真地使用conn.recv()会让你过得很糟糕;不能保证另一端发送的任何数据都在一个数据包中发送(即,您将在一个recv()调用中获得您期望的所有数据(。

最新更新