Implemented logic to handle connection loss  and for reconnecting.