This is my code for connecting to a multicast server, is this the best way of handling the exception. What I would like to do is to retr开发者_C百科y to connect if an exception occurs
def initialiseMulticastTrackerComms():
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 32)
sock.bind((ANY, MCAST_PORT))
host = socket.gethostbyname(socket.gethostname())
sock.setsockopt(socket.SOL_IP, socket.IP_ADD_MEMBERSHIP,socket.inet_aton(MCAST_GRP) + socket.inet_aton(host))
sock.setblocking(False)
except socket.error, (value,message):
print "Could not open socket: " + message
sys.exit(1)
else:
print 'Connected to multicast server'
return sock
Could someone offer any advice on how to do this
Thanks in advance
The simplest solution would be to wrap your try-except-else block in a loop.
Something like this
def initSock():
message = ""
for i in range(MAX_TRIES):
try:
#...socket opening code
except socket.error, (value, message):
message = message
else:
print "Connected"
return sock
print "Could not open socket: " + message
sys.exit(1)
精彩评论