亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何正確設置 Python 套接字服務器

如何正確設置 Python 套接字服務器

哈士奇WWW 2021-08-17 18:52:33
我最近開始學習 Python,但遇到了一個問題。為什么當我執行 socket.accept() 時我的 while True 循環會停止我的代碼會不斷打印“嘿??!”: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!!”的問題 還要讓插座工作?謝謝閱讀!更新:它現在正在工作,我正在使用線程來實現它。你有同樣的問題嗎?-> 谷歌:“Multiple while true loops threading python”感謝所有幫助我的人!
查看完整描述

1 回答

?
倚天杖

TA貢獻1828條經驗 獲得超3個贊

為什么當我執行 socket.accept() 時我的 while True 循環會停止

accept是一個阻塞操作。它一直等到客戶端連接。它在客戶端連接后繼續并返回新客戶端連接的套接字。

我的代碼只打印 'HEY!!' 一次:

HEY!!如果客戶端連接到您的服務器,它將打印不止一次,因此阻塞accept返回。


查看完整回答
反對 回復 2021-08-17
  • 1 回答
  • 0 關注
  • 142 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號