我認爲,如果你不能夠連接到服務器的你,如果你捕獲異常以下將要執行的行會自動拋出一個異常。
例如: -
客戶端
import socket
import struct, time
import sys
# server
HOST = "localhost"
PORT = 13
# reference time (in seconds since 1900-01-01 00:00:00)
TIME1970 = 2208988800L # 1970-01-01 00:00:00
# connect to server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s2 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.connect((HOST, PORT))
except: # catch *all* exceptions
e = sys.exc_info()[0]
print(e)
try:
s2.connect((HOST, 8037))
except: # catch *all* exceptions
e = sys.exc_info()[0]
# read 4 bytes, and convert to time value
t = s2.recv(4)
t = struct.unpack("!I", t)[0]
t = int(t - TIME1970)
s.close()
# print results
print "server time is", time.ctime(t)
print "local clock is", int(time.time()) - t, "seconds off"
服務器端
import socket
import struct, time
# user-accessible port
PORT = 8037
# reference time
TIME1970 = 2208988800L
# establish server
service = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
service.bind(("", PORT))
service.listen(1)
print "listening on port", PORT
while 1:
# serve forever
channel, info = service.accept()
print "connection from", info
t = int(time.time()) + TIME1970
t = struct.pack("!I", t)
channel.send(t) # send timestamp
channel.close() # disconnect
在上述客戶端代碼的一個服務器端口不退出即本地主機:13,從而它會拋出異常,並且我發現異常並且比錯誤之後的代碼代碼已執行,因此連接到服務器localhost:8037並返回數據。
先生,我想執行的程序休息即使服務器有故障或不connected.or任何其他錯誤發生。如果我設置超時()它顯示超時。或生成錯誤消息。請給我舉一個例子 –