Fix heartbeat behaviour after connection failure.

Make sure socket is closed and heartbeat is not executed when no longer active.

This is one way to fix issue #502