我有两个服务器,我的客户端想要向两个服务器发送相同的数据。但是如果server1无法连接客户端程序等待而server2没有获取数据。我想等一下server1如果连接失败,那么server2将获得数据。
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()
答案 0 :(得分: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()
答案 1 :(得分: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
在上面的客户端代码中,一个服务器端口没有退出,即localhost:13,因此它将抛出异常并且我捕获异常,而不是执行错误代码后的代码,因此连接到服务器localhost:8037并返回数据。