简体   繁体   English

使用Python连接到多播服务器

[英]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. 最简单的解决方案是将try-except-else块包装在一个循环中。

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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