Python UDP socket resend data if no data recieved -


i want send data sensor , if python script doesn't receive data want receive function timeout , resend 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 light successful')    else:        logging.info('subscribition 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 moment gets stuck in receive function if doesn't receive data:

data, addr = sock.recvfrom(1024) 

however want timeout after e.g. 2 seconds , rerun subscribe() function.

i've tried using while true statement timeout , try/exception port in use when closing port. feel way messy.

any ideas appreciated.

you "currently in use" exception because recreating sockets every time call either of functions, without closing them first.

try creating sockets beforehand. response might come before receiving socket created in case packet going rejected.

then should try sendto-recvfrom calls in loop.

also either need set timeout settimeout on receiving socket not blocked catch timeout exception or use polling mechanism select or poll check whether have received data.


Comments

Popular posts from this blog

jOOQ update returning clause with Oracle -

java - Warning equals/hashCode on @Data annotation lombok with inheritance -

java - BasicPathUsageException: Cannot join to attribute of basic type -