Socket输入处理逻辑陷入循环问题排查求助
Socket接收代码输入错误时陷入循环问题排查
我正在开发一段Socket接收代码,能正常接收Socket输入,但输入错误内容时程序会陷入循环,无法等待新输入。希望程序能等待新输入,求助排查循环卡顿原因。
Socket接收代码
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"写法完全错误。Python中该逻辑会被解析为(continue_q != "y") or ("Y") or ("n") or ("N"),而非空字符串在布尔判断中永远为True,导致这个条件永远成立,代码会一直进入该分支循环。
正确的条件写法
应判断continue_q不在指定的合法值列表中,同时建议去除接收内容中可能带的换行、空格:
if continue_q.strip() not in {"y", "Y", "n", "N"}:
其他优化点
- 移除
time.sleep(5):conn.recv()本身是阻塞调用,会自动等待新输入,无需额外延迟。 - 增加空数据判断:Socket接收的
data可能为空(客户端断开连接),需处理避免解码报错:
data = conn.recv(2042) if not data: print("Client disconnected") return -1
修改后的完整代码示例
data = conn.recv(2042) if not data: print("Client disconnected") return -1 line = data.decode('UTF-8').strip() continue_q = line while True: if continue_q not in {"y", "Y", "n", "N"}: print("atgorboge") print("please address errors. continue? (Y/N)") data = conn.recv(2042) if not data: print("Client disconnected") return -1 line = data.decode('UTF-8').strip() continue_q = line if continue_q in {"y", "Y"}: print('poped to yes') clear_json_flags(DEBUG_PRINT, WC) update_json_file(DEBUG_PRINT, CONFIG_FILE, WC) return 0 if continue_q in {"n", "N"}: print('poped to no') return -1
内容的提问来源于stack exchange,提问作者Munix0
相关产品推荐
相关产品推荐

