HeartBeat thread will never finish

Added a check for a closed socket