python - How to re-establish asyncore connection with server (solved) -
i have asyncore client interacts server written in c. need able detect when server closes connection , keep re-trying connect until available again. here code have: asyncore client turn starts threaded module (receiverboard) run in separate thread. class detclient(asyncore.dispatcher):
buffer = "" t = none def __init__(self, host, port): asyncore.dispatcher.__init__(self) self.create_socket(socket.af_inet, socket.sock_stream) self.connect((host,port)) self.host=host self.port=port self.t = receiverboard(self) self.t.start() def sendcommand(self, command): self.buffer = command def handle_error(self): self.t.stop() self.close() def handle_write(self): sent=self.send(self.buffer.encode()) self.buffer="" def handle_read(self): ##there code here parse received message , call appropriate ##method in threaded module receiverboard
my first problem wanted client (above) keep retrying connect server (developed in ansi c) through socket until connection made.
the change made override handle_error method in asyncore above call method try initialize connection again instead of closing socket. in below: (following code added detclient above)
def initiate_connection_with_server(self): print("trying initialize connection server...") asyncore.dispatcher.__init__(self) self.create_socket(socket.af_inet, socket.sock_stream) self.connect((self.host,self.port)) def handle_error(self): print("problem reaching server.") self.initiate_connection_with_server()
this solves problem of server not being available when code run. exception raised , handle_error called calls initiate_connection method , tries open socket again. also, after connection established, code call handle_error if socket lost reason , attempt made re-establish connection. problem solved!
here code threaded module (receiverboard)
class receiverboard(threading.thread): _stop = false def __init__(self, client): self.client=client super(receiverboard,self).__init__() def run(self): while true: block_to_send = "" ##code here generate block_to_send self.client.sendcommand(block_to_send) def stop(self): self._stop = true
Comments
Post a Comment