【问题标题】:why do i get a bad file descriptor error?为什么我会收到错误的文件描述符错误?
【发布时间】:2016-08-26 06:28:35
【问题描述】:

我为我制作的 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

谁能告诉我我是怎么得到这个错误的以及如何解决它?

【问题讨论】:

    标签: python python-2.7 sockets server


    【解决方案1】:

    您收到此错误是因为您 close 套接字然后再次调用 recvfrom

    如果您在 recvfrom 行之后添加 print,您会注意到对 recvfrom 的第一次调用按预期工作。第二次调用(循环一次后)抛出您看到的错误。

    只需删除 s.close() 即可修复您的代码。 (你不需要关闭与客户端的连接,因为 UDP 没有这个概念,如果你有这个概念,与 TCP 形成对比。)

    【讨论】:

      【解决方案2】:

      如果你有一个无限的while循环,你会得到同样的错误。就我而言,我更换了

      while True:
      

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

      【讨论】:

      • 但是如果你想要一个无限的while循环呢?
      • 这将如何导致错误?我已经编写了很多依赖无限循环运行直到发生某些事情的程序,但我从未遇到过这样的问题。
      猜你喜欢
      • 2013-12-02
      • 2012-03-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-08
      • 1970-01-01
      相关资源
      最近更新 更多