Added code to handle the case of losing connection