[英]Testing socket connection in Python
這個問題將擴展到: Best way to open a socket in Python
打開套接字時,我如何測試以查看它是否已建立,並且它沒有超時,或者通常會失敗。
編輯:我試過這個:
try:
s.connect((address, '80'))
except:
alert('failed' + address, 'down')
但是即使該連接應該正常工作,也會調用警報功能。
似乎你捕捉到的不是你想要捕捉的異常:)
如果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()
始終嘗試查看您在 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!"
你真的應該發帖:
這是我的代碼,它有效:
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))
當服務器偵聽時,我什么也沒得到(這是正常的),當它沒有偵聽時,我得到預期的消息:
Something's wrong with ('::1', 80, 0, 0). Exception type is (111, 'Connection refused')
12 年后,對於任何有類似問題的人。
try:
s.connect((address, '80'))
except:
alert('failed' + address, 'down')
不起作用,因為端口 '80' 是一個字符串。 您的端口需要是 int。
try:
s.connect((address, 80))
這應該有效。 不知道為什么即使是最好的答案也沒有看到這一點。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.