这个问题将扩展:在Python中打开套接字的最佳方法打开套接字时,
我如何测试它是否已经建立,并且它没有超时,或者通常会失败.
编辑:我试过这个:
try:
s.connect((address, '80'))
except:
alert('failed' + address, 'down')
Run Code Online (Sandbox Code Playgroud)
但即使该连接应该有效,也会调用alert函数.
ken*_*der 39
看来你抓住的不是你想要赶上的例外:)
如果s是一个socket.socket()对象,那么正确的调用.connect方式是:
import socket
s = socket.socket()
address = '127.0.0.1'
port = 80 # port number is a number, not string
try:
s.connect((address, port))
# originally, it was
# except Exception, e:
# but this syntax is not supported anymore.
except Exception as e:
print("something's wrong with %s:%d. Exception is %s" % (address, port, e))
finally:
s.close()
Run Code Online (Sandbox Code Playgroud)
总是试着看看你在try-except循环中捕获的是什么类型的异常.
您可以检查套接字模块中的哪些类型的异常代表什么类型的错误(超时,无法解析地址等)并except为每个错误单独生成语句 - 这样您就可以对不同类型的错误做出不同的反应问题.
您可以使用connect_ex函数.它没有抛出异常.而不是那样,返回一个C样式的整数值(在C中称为errno):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = s.connect_ex((host, port))
s.close()
if result:
print "problem with socket!"
else:
print "everything it's ok!"
Run Code Online (Sandbox Code Playgroud)
你应该发帖:
这是我的代码,它有效:
import socket, sys
def alert(msg):
print >>sys.stderr, msg
sys.exit(1)
(family, socktype, proto, garbage, address) = \
socket.getaddrinfo("::1", "http")[0] # Use only the first tuple
s = socket.socket(family, socktype, proto)
try:
s.connect(address)
except Exception, e:
alert("Something's wrong with %s. Exception type is %s" % (address, e))
Run Code Online (Sandbox Code Playgroud)
当服务器监听时,我什么也得不到(这是正常的),当它没有时,我得到了预期的消息:
Something's wrong with ('::1', 80, 0, 0). Exception type is (111, 'Connection refused')
Run Code Online (Sandbox Code Playgroud)