获取Errno 9: python套接字中的坏文件描述符

时间:2021-01-11 20:30:43

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"

2 个解决方案

#1


35  

You're calling connect on the same socket you closed. You can't do that.

您正在调用您关闭的相同套接字上的connect。你不能这样做。

As for the docs for close say:

至于文件的近况:

All future operations on the socket object will fail.

socket对象未来的所有操作都将失败。

Just move the s = socket.socket() (or whatever you have) into the loop. (Or, if you prefer, use create_connection instead 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,而不是在两个步骤中使用create_connection,这将使问题变得更加困难,也意味着您不必猜测IPv4和IPv6等等)。

#2


1  

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

#1


35  

You're calling connect on the same socket you closed. You can't do that.

您正在调用您关闭的相同套接字上的connect。你不能这样做。

As for the docs for close say:

至于文件的近况:

All future operations on the socket object will fail.

socket对象未来的所有操作都将失败。

Just move the s = socket.socket() (or whatever you have) into the loop. (Or, if you prefer, use create_connection instead 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,而不是在两个步骤中使用create_connection,这将使问题变得更加困难,也意味着您不必猜测IPv4和IPv6等等)。

#2


1  

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