我最近開始學(xué)習(xí) Python,但遇到了一個問題。為什么當(dāng)我執(zhí)行 socket.accept() 時我的 while True 循環(huán)會停止我的代碼會不斷打印“嘿??!”:import sockethost = "0.0.0.0" #<- Not the real port and ip, I have working ones...port = 1234s = socket.socket()s.bind((host, port))s.listen(5)while True: print("HEY!!") ''' connection, adress = s.accept() print("Got connection from: '" + str(adress[0]) + ":" + str(adress[1]) + "'") '''我的代碼只打印 'HEY!!' 一次:import sockethost = "0.0.0.0" #<- Not the real port and ip, I have working ones...port = 1234s = socket.socket()s.bind((host, port))s.listen(5)while True: print("HEY!!") connection, adress = s.accept() print("Got connection from: '" + str(adress[0]) + ":" + str(adress[1]) + "'")我該如何解決它不斷打印“HEY!!”的問題 還要讓插座工作?謝謝閱讀!更新:它現(xiàn)在正在工作,我正在使用線程來實現(xiàn)它。你有同樣的問題嗎?-> 谷歌:“Multiple while true loops threading python”感謝所有幫助我的人!
1 回答

倚天杖
TA貢獻1828條經(jīng)驗 獲得超3個贊
為什么當(dāng)我執(zhí)行 socket.accept() 時我的 while True 循環(huán)會停止
accept
是一個阻塞操作。它一直等到客戶端連接。它在客戶端連接后繼續(xù)并返回新客戶端連接的套接字。
我的代碼只打印 'HEY!!' 一次:
HEY!!
如果客戶端連接到您的服務(wù)器,它將打印不止一次,因此阻塞accept
返回。
添加回答
舉報
0/150
提交
取消