I think it will automatically throws an exception if you are not able to connect to server you if you catch the exception the lines following will be executed.
for example:-
client side
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"
Server Side
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
In the above client code one server port does not exit i.e localhost:13 so it will throw exception and i caught the exception and than the code following the erroneous code executed and hence connected to sever localhost:8037 and it returned the data.