Check for valid socket before trying to close the connection