简体   繁体   中英

Connecting to a Multicast Server in Python

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 retry 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM