获取 Errno 9:python 套接字中的错误文件描述符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15958026/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getting Errno 9: Bad file descriptor in python socket
提问by Mike Savi
My code is this:
我的代码是这样的:
while 1:
# Determine whether the server is up or down
try:
s.connect((mcip, port))
s.send(magic)
data = s.recv(1024)
s.close()
print data
except Exception, e:
print e
sleep(60)
It works fine on the first run, but gives me Errno 9 every time after. What am I doing wrong?
它在第一次运行时运行良好,但每次都给我 Errno 9。我究竟做错了什么?
BTW,
顺便提一句,
mcip = "mau5ville.com"
port = 25565
magic = "\xFE"
采纳答案by abarnert
You're calling connecton the same socket you closed. You can't do that.
您正在调用connect您关闭的同一个套接字。你不能那样做。
As for the docsfor closesay:
至于该文档的close说:
All future operations on the socket object will fail.
套接字对象上的所有未来操作都将失败。
Just move the s = socket.socket()(or whatever you have) into the loop. (Or, if you prefer, use create_connectioninstead of doing it in two steps, which makes this harder to get wrong, as well as meaning you don't have to guess at IPv4 vs. IPv6, etc.)
只需将s = socket.socket()(或任何您拥有的)移动到循环中即可。(或者,如果您愿意,可以使用create_connection而不是分两步进行,这样更难出错,也意味着您不必猜测 IPv4 与 IPv6 等。)
回答by mgrfn
i resolved this problem at the past,
我过去解决了这个问题,
you have to make this before connect again:
您必须在再次连接之前进行此操作:
s = socket(AF_INET, SOCK_STREAM)
than continue with:
比继续:
s.connect((mcip, port))
s.send(magic)
data = s.recv(1024)
s.close()
print dat

