python - Test a pair of network sockets at the same time -
i have app x can run on either of 2 computers, on no more 1 @ once. have app y, written in python, given 2 possible ip addresses needs find out computer running app x (if any). i've partially solved having udp service listens on port , responds 'hello' whenever receives data. client can try , send data app x port on each address , if gets response, know application running on computer.
my code far looks this:
def ipaddress(self): """test side responds on status port.""" s = socket.socket(socket.af_inet, socket.sock_dgram) try: s.settimeout(5) s.sendto("status", (addr_a, port)) s.recvfrom(1024) except socket.timeout: try: s.sendto("status", (addr_b, port)) s.recvfrom(1024) except: pass else: return addr_b else: return addr_a finally: s.close() return none
the problem function it's called periodically whenever want talk computer running app x. test addr_a first, , if it's not running app x have wait socket timeout before trying addr_b. although doesn't happen app x have switched computers whenever come around trying again.
is there better way? i'm wondering if it's possible connect both computers in parallel , return 1 responds? or should cache ip address responded first last time function called? how code these or other ideas?
thanks.
edit: here revised code using select:
def ipaddress(addr_a, addr_b, timeout=5): """test side responds on status port.""" # create udp sockets each address socks = [ socket.socket(socket.af_inet, socket.sock_dgram), socket.socket(socket.af_inet, socket.sock_dgram) ] # send data each socket sock, addr in zip(socks, (addr_a, addr_b)): sock.connect(addr) # explicit connect getpeername works sock.send("status") # wait first respond if while socks: waiting = select.select(socks, [], socks, timeout)[0] if waiting: sock in waiting: try: data = sock.recv(1024) if data: return sock.getpeername()[0] except exception, e: # [errno 10054] means socket isn't # available, see if other responds instead... socks.remove(sock) else: break # timeout occurred return none
you should @ select.select() provides capability looking @ 2 computers in parallel.
Comments
Post a Comment