为什么我收到错误的文件描述符错误? [英] why do i get a bad file descriptor error?

查看:113
本文介绍了为什么我收到错误的文件描述符错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于我制作的 udp 服务器程序的这段代码,我收到了错误的文件描述符错误

i got an error for bad file descriptor for this code for the udp server program i made

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

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

can anyone please tell me how i got this error and how to solve it?

推荐答案

您收到此错误是因为您关闭 套接字,然后再次调用 recvfrom.

You get this error because you close the socket and then call recvfrom again.

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

If you add a print after the line with recvfrom, you'll notice that the first call to recvfrom works as expected. The second call (after looping once) throws the error you see.

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

Fix your code by simply removing s.close(). (You don't need to close the connection to the client as UDP doesn't have that concept, in contrast to TCP if you had that in mind.)

这篇关于为什么我收到错误的文件描述符错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆