1

I want to send some data to a sensor and if the python script doesn't receive the data I want the receive function to timeout and resend the data.

def subscribe():
   UDP_IP = "192.168.1.166"
   UDP_PORT = 10000
   MESSAGE = '6864001e636caccf2393730420202020202004739323cfac202020202020'.decode('hex')
   print "UDP target IP:", UDP_IP
   print "UDP target port:", UDP_PORT
   print "message:", MESSAGE
   sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
   sock.sendto(MESSAGE, (UDP_IP, UDP_PORT))
   recieve_data = recieve()
   if recieve_data == subscribe_recieve_on or recieve_data == subscribe_recieve_off:
       logging.info('Subscribition to light successful')
   else:
       logging.info('Subscribition to light unsuccessful')

def recieve():
   UDP_IP = "192.168.1.118"
   UDP_PORT = 10000
   sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # UDP    
   sock.bind((UDP_IP, UDP_PORT))
   data, addr = sock.recvfrom(1024)
   return data.encode('hex')

subscribe()

At the moment it gets stuck in the receive function if it doesn't receive any data:

data, addr = sock.recvfrom(1024)

However I want it to timeout after e.g. 2 seconds and rerun the subscribe() function.

I've tried using a while true statement with a timeout and try/exception however I get a port currently in use even when closing the port. Also feel this way is messy.

Any ideas would be appreciated.

4

1 回答 1

1

您会得到“当前正在使用”异常,因为每次调用其中任何一个函数时都在重新创建套接字,而没有先关闭它们。

尝试预先创建套接字。响应可能会在创建接收套接字之前出现,在这种情况下,数据包将被拒绝。

那么你应该只尝试循环中的sendto-recvfrom调用。

此外,您需要在接收套接字上使用settimeout设置超时,以便它不会被阻塞然后捕获超时异常,或者使用诸如selectpoll之类的轮询机制来检查您是否收到任何数据。

于 2016-07-25T18:59:43.197 回答