Fix heartbeat behaviour after connection failure.

Make sure socket is closed and heartbeat is not executed when no longer active.