Python:如何区分套接字错误和超时?

2024-04-20 00:35:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下代码:

try:
    while 1:
        s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
        s.settimeout(5);
        s.connect((HOST,PORT))
        print("before send")
        #time.sleep(10);
        #s.sendall('GET / HTTP/1.1\r\nConnection: Keep-Alive\r\nHost: www.google.lt\r\n\r\n')
        data=s.recv(52)
        print("after send");
        s.close()
        if string.find(data,"HTTP/1.1 200 OK") == -1:
            print("Lost Connection")
        print(data)
        time.sleep(2)
except keyboardInterrupt:
    print("CTRL C occured")
except socket.error:
    print("socket error occured: ")
except socket.timeout:
    print("timeout error")

我已经评论了sendall函数来测试recv如何生成超时异常。 但问题是我得到了socket.error异常。 如果我将最后一行代码更改为:

except socket.timeout:
    print("timeout error")
except socket.error:
     print("socket error occured: ")

然后我得到socket.timeout异常。 那么真正产生的异常是什么呢?


Tags: 代码sendhttpdatatimetimeoutsleeperror
1条回答
网友
1楼 · 发布于 2024-04-20 00:35:00

socket.timeoutsocket.error的一个子类。真的是socket.timeout。当您首先捕获一个socket.error时,您将捕获一个更一般的情况。

>>> issubclass(socket.timeout, socket.error)
True

此代码正确:

except socket.timeout:
 print("timeout error")
except socket.error:
 print("socket error occured: ")

试着特别捕捉socket.timeout,然后捕捉其他socket.error

相关问题 更多 >