2015-05-04 96 views
2

我有兩臺服務器,我的客戶端想要發送相同的數據到兩個server.but但如果server1無法連接客戶端程序等待和server2沒有獲取數據。如果服務器1連接失敗,我想等待1秒,然後服務器2將獲取數據。如何不退出服務器連接,如果沒有連接

import socket    
s1 = socket.socket()  
s2 = socket.socket() 
host1 = '192.168.0.3' 
port1 = 12345 
host2 = '192.168.0.5' 
port2=12321    
s1.connect((host1, port1)) 
s1.send(data) 
s2.connect((host2,port2)) 
s2.send(data) 
s1.close() 
s2.close() 

回答

1

只需加試

try: 
    s1.connect((host1, port1)) 
    s1.send(data) 
except: 
    print " s1 not connected" 
try: 
    s2.connect((host2,port2)) 
    s2.send(data) 
except: 
    print"s2 not connected" 
s1.close() 
s2.close() 
0

我認爲,如果你不能夠連接到服務器的你,如果你捕獲異常以下將要執行的行會自動拋出一個異常。
例如: -
客戶端

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並返回數據。

+0

先生,我想執行的程序休息即使服務器有故障或不connected.or任何其他錯誤發生。如果我設置超時()它顯示超時。或生成錯誤消息。請給我舉一個例子 –