2016-05-01 35 views
3

我得到了錯誤的文件描述符的錯誤此代碼爲UDP服務器程序我做爲什麼我得到一個錯誤的文件描述符錯誤?

from socket import * 

s = socket(AF_INET, SOCK_DGRAM) 
s.bind(('', 890)) 

while True: 
    (c,a) = s.recvfrom(1024) 
    msg = 'thanks for requesting' 
    s.sendto(msg,a) 
    s.close() 

錯誤消息我得到的是

Traceback (most recent call last): 
File "udpserv.py", line 7, in <module> 
(c,a) = s.recvfrom(1024) 
File "/usr/lib/python2.7/socket.py", line 174, in _dummy 
raise error(EBADF, 'Bad file descriptor') 
socket.error: [Errno 9] Bad file descriptor 

誰能請告訴我如何得到這個錯誤以及如何解決它?

回答

4

你得到這個錯誤是因爲你的套接字是close,然後再次調用recvfrom

如果您在recvfrom後添加print,您會注意到recvfrom的第一個呼叫按預期工作。第二次調用(循環一次後)會引發你看到的錯誤。

通過簡單地刪除s.close()來修復您的代碼。 (你不需要關閉與客戶端的連接,因爲UDP沒有這個概念,相反,如果你有這個想法,TCP就可以)。

0

如果你有一個無限的時間,你可以得到同樣的錯誤循環。在我來說,我與

count = 0 
while (count < 10): 
    count += 1 
    #rest of the code 
取代

while True: