Sen. John McCain has died. He was 81 years old.

A war hero who would go on to Congress and run for president, McCain survived plane crashes, several bouts of skin cancer and brushes with political oblivion, often seemed to be perpetually waging a race against time and his own mortality while striving to ensure that his five-and-a-half years as a Vietnam prisoner of war did not stand as the defining experience of his life.

He spent his last few months out of the public eye in his adopted home state of Arizona, reflecting on the meaning of his life and accepting visits from a stream of friends and old political combatants.

In a memoir published in May, McCain wrote that he hated to leave the world, but had no complaints.

"It's been quite a ride. I've known great passions, seen amazing wonders, fought in a war, and helped make peace," McCain wrote. "I've lived very well and I've been deprived of all comforts. I've been as lonely as a person can be and I've enjoyed the company of heroes. I've suffered the deepest despair and experienced the highest exultation.

"I made a small place for myself in the story of America and the history of my times."

McCain had not been in Washington since December, leaving a vacuum in the corridors of the Senate and the television news studios he roamed for decades.

In recent months, he was not completely quiet, however, blasting President Donald Trump in a series of tweets and statements that showed that while he was ailing he had lost none of his appetite for the political fight.

The Arizona Senator repeatedly made clear that he saw Trump and his America First ideology as a departure from the values and traditions of global leadership that he saw epitomized in the United States.

CNN reported in May, that the McCains did not want Trump at his funeral. Former rivals and Presidents Barack Obama and George W. Bush had been asked to give eulogies, people close to both former presidents and a source close to the senator confirmed to CNN.

McCain's two losing presidential campaigns meant he fell short of the ultimate political prize, one his story once seemed to promise after he came home from Vietnam and caught the political bug. In the end, he became a scourge of presidents rather than President himself.

At the time of his death, he was largely an anomaly in his own party -- as one of the few Republicans willing to criticize Trump and a believer in the idealized "shining city on a hill" brand of conservatism exemplified by his hero Ronald Reagan that has been dislodged by the nativist and polarizing instincts of the current President. He was also a throwback to an earlier era when political leaders, without betraying their own ideology, were willing on occasion to cross partisan lines.

In a Washington career that spanned 40 years, first as a Navy Senate liaison, then as a member of the House and finally as the occupant of the Senate seat he took over from Barry Goldwater, McCain was a conservative and a foreign policy hawk. But he was not always a reliable Republican vote, and sometimes in a career that stretched into a sixth Senate term, he confounded party leaders with his maverick stands. He defied party orthodoxy to embrace campaign finance reform, and excoriated President George W. Bush's defense secretary, Donald Rumsfeld, for not taking enough troops to Iraq.

After Obama ended McCain's second White House race in 2008, the senator blasted the new President's troop withdrawals from Iraq and Afghanistan, causing critics to carp that he had not yet reconciled the bitterness he felt in defeat. McCain had supported the invasion of Iraq carried out by the Bush administration in 2003, but admitted in his memoir "The Restless Wave" that the rationale, that Saddam Hussein had weapons of mass destruction was wrong.

"The war, with its cost in lives and treasure and security, can't be judged as anything other than a mistake, a very serious one, and I have to accept my share of the blame for it," he wrote.

More recently, as death approached, he became a strident critic of Trump, who had once said he didn't consider the Arizona senator a war hero because he had been captured.

McCain questioned why Trump was solicitous of Vladimir Putin, whom he regarded as an unreformed KGB apparatchik.

In one of his final public acts, he blasted Trump's cozy summit with the Russian President in July, blasting it as "one of the most disgraceful performances by an American president in memory."

"The damage inflicted by President Trump's naiveté, egotism, false equivalence, and sympathy for autocrats is difficult to calculate. But it is clear that the summit in Helsinki was a tragic mistake," he said in a statement.

In July 2017, McCain returned from brain surgery to the Senate floor to lambaste "bombastic loudmouths" on the television, radio and internet and plead for a return to a more civilized political age, when compromise and regular order forged bipartisan solutions.

Then, in September, in a poignant speech that seemed designed to echo down the ages after he was gone, McCain reminded his colleagues they were a check on executive power: "We are not the President's subordinates," he said. "We are his equals."

In a final act of defiant independence, McCain, with a dramatic thumbs-down gesture on the Senate floor in September, cast the vote that scuttled the GOP's effort to repeal and replace Obamacare, causing fury within his party -- a move that prompted Trump, to the fury of McCain's family to repeatedly single him out in campaign rallies.

When the President signed McCain's last legislative triumph in August, the John S. McCain National Defense Authorization Act, he did not even mention the Arizona senator.

'I wasn't my own man anymore; I was my country's'

John Sidney McCain III, the son and grandson of Navy admirals, entered the world on August 29, 1936, in the Panama Canal Zone, a birthplace that years later would cause a brief campaign kerfuffle over whether he was a natural born citizen and thus eligible to be elected president.

His habit of insubordination despite his military pedigree emerged at the Naval Academy, where he graduated fifth from the bottom of his class.

"My superiors didn't hold me in very high esteem in those days. Their disapproval was measured in the hundreds of miles of extra duty I marched in my time here," McCain told graduates at Annapolis in October of last year.

By 1967, McCain was in the Pacific and escaped death in a massive fire aboard the USS Forrestal aircraft carrier. Months later, he was shot down in his Skyhawk jet over North Vietnam and parachuted into a lake near Hanoi, breaking both arms and a leg, and was captured by communist soldiers. In captivity, McCain was tortured and beaten, an experience that left him with lifelong injuries, including severely restricted movement of his arms. He kept himself sane by tapping on a wall to communicate with a fellow prisoner in a neighboring cell. Later, he refused the offer of a preferential release, made because his father was an admiral, until his comrades could also come home, eventually returning in 1973 to a nation politically torn by the war.

His period in captivity set the course of his life.

"I fell in love with my country when I was a prisoner in someone else's," McCain said in his 2008 Republican National Convention speech.

"I loved it because it was not just a place, but an idea, a cause worth fighting for. I was never the same again; I wasn't my own man anymore; I was my country's."

After turning to politics, McCain served in the House from 1983, won an Arizona US Senate seat in 1986 and established himself as a down-the-line conservative in the age of Ronald Reagan. But his political career almost fizzled before it began when he was among the Keating Five group of senators accused of interfering with regulators in a campaign finance case. He was cleared of wrongdoing, but the Senate Ethics Committee reprimanded him for poor judgment, an experience that led to him becoming a pioneer of campaign finance reform.

He didn't forget his time in Vietnam.

In an act of reconciliation, McCain joined Democratic Sen. John Kerry of Massachusetts, a fellow decorated Vietnam War veteran, to help end the US trade embargo on its former southeast Asian enemy in a process that led to the eventual reopening of diplomatic relations.

By 2000, McCain set his sights on the White House and ran as a maverick Republican, holding court for hours in candid back-and-forth sessions with reporters on his campaign bus, dubbed the "Straight Talk Express." In years to come, he would joke that his adoring press pack was his "base."

After skipping Iowa over his long opposition to ethanol subsidies, McCain forged a victory over establishment favorite and then-Texas Gov. George W. Bush in New Hampshire after a string of town hall meetings with voters.

But his effort hit a brick wall in South Carolina, where the campaign turned negative and McCain's independent streak hurt him in a state with more core conservatives and fewer independents. Bush got back on track with a primary win that set him on the road to the nomination.

The maverick of the Senate

Back in the Senate, McCain heard the call of war again, as American foreign policy was transformed after the September 11, 2001, terror attacks, and he became a forceful proponent of the US use of force overseas. He backed US interventions in Afghanistan and Iraq. When Americans tired of war, McCain warned that more troops were needed, demanding a surge in forces that Bush later adopted.

When it appeared that his hawkish views were at odds with the electorate and could damage his nascent 2008 presidential bid, McCain answered: "I would rather lose a campaign than a war."

But, influenced by his experience of torture in Vietnam, McCain was a forceful critic of the enhanced interrogation techniques used by the CIA on terror suspects, believing they were contrary to American values and damaged the US image abroad.

It was a typical example of the Arizona senator adopting a position that appeared antithetical to his political interests or ran counter to the perceived wisdom of his party.

After the Keating Five scandal, he joined a crusade with Democratic Sen. Russ Feingold of Wisconsin to introduce new restrictions on "soft" and corporate money in political campaigns.

Later, McCain teamed up with his great friend, late Massachusetts Democratic Sen. Edward Kennedy on a bill that would provide a path to citizenship for undocumented immigrants. The measure failed, however, over building grassroots antipathy to such a move in the GOP, which would later play a major role in the Trump campaign in the 2016 election.

McCain set his sights on the White House again during Bush's second term. By 2007, his campaign was all but broke. But he fired up the Straight Talk Express again and pulled off another famous comeback, barnstorming to victory once more in the New Hampshire primary.

This time, he also won South Carolina, and beat a fading Mitt Romney and Rudy Giuliani in Florida before effectively clinching the nomination with a clutch of wins on Super Tuesday.

That November, McCain came up against the historic appeal of a much younger and more eloquent rival, Obama. Mocking the Illinois senator in ads as "the biggest celebrity in the world," McCain questioned whether his popular foe was ready to lead.

Seeking to rebrand himself in a change election, McCain stunned the political world by picking little-known Sarah Palin as his running mate. The Alaska governor delivered a spellbinding convention speech, and for several weeks it seemed as if McCain's gamble worked.

But a series of gaffes turned Palin into a figure of ridicule and undercut McCain's contention that his ticket, and not Obama's, was best qualified to lead in a dangerous world. McCain, however, would not say that he regretted picking Palin.

But in his new memoir, "The Restless Wave," and in a separate documentary, McCain said he wished he had ignored the advice of his advisers and listened to his gut and chosen Sen. Joe Lieberman of Connecticut, a Democrat-turned-independent, calling it "another mistake that I made."

But McCain also rose above the ugliness of the campaign. On one occasion, he cut off a supporter at a town hall event who said she could not trust Obama because she thought he was an Arab, amid conspiracy theories suggesting that the Democrat had not been not born in America.

"No ma'am, he's a decent family man, citizen, who I just happen to have disagreements with on fundamental issues, and that's what this campaign is all about," McCain said.

He dealt with his defeat by throwing himself back into life in the Senate. In later years he described how it felt to lose, telling anyone who asked, "After I lost ... I slept like a baby — sleep two hours, wake up and cry."

But his relationship with Obama was tense, with the President snubbing his former foe in a health care summit in 2010 by telling him "the election's over."

The Arizona senator emerged as a fierce critic of Obama's worldview, prompting Democrats to complain that McCain was the embodiment of a Republican reflex to respond to every global problem with military force, which had led America into misadventures like the war in Iraq.

McCain's robust foreign policy views were reflected on the walls of his Senate conference room, which featured letters and photos from the likes of Reagan and Margaret Thatcher, leaders who didn't suffer critics gladly.

Still, McCain was also a throwback, enjoying friendships with rivals across the political aisle, and indulging in the back-slapping bonhomie of the Senate, where he invariably held court to a crowd between votes.

Sometimes things got testy with his Democratic pals, including when he confronted Hillary Clinton and fellow Vietnam War veteran Kerry during hearings of the Senate Armed Services Committee while they served as secretaries of state under Obama.

'He served his country... and, I hope we could add, honorably'

The Republicans' recapture of the Senate in the 2014 midterm elections gave McCain a chance to rewrite the final chapter of his career.

He at last took the gavel of the Armed Services Committee, an assignment he had long coveted. His prominent position was seen as one reason he ran for re-election in 2016.

But he knew his time was limited.

"Every single day," McCain told The New York Times in 2015, "is a day less that I am going to be able to serve in the Senate."

Still, despite saying he was "older than dirt," McCain made few concessions to his age. Even after turning 80, he maintained a punishing schedule of world travel, conferring with top leaders and heading to war zones in trips that left his younger congressional colleagues exhausted.

He would blitz Sunday talk shows, direct from Arizona in the dawn hours. When Trump was elected, McCain took it upon himself to reassure world leaders, visiting multiple countries in the first six months of 2017 before his diagnosis.

His sidekick, GOP Sen. Lindsey Graham of South Carolina, told CNN the hectic pace had taken a toll.

"You know he just wore himself out traveling all around the world," Graham said.

McCain, who was divorced from his first wife, Carol, in 1980, is survived by his wife, Cindy, seven children, including three sons who continued the family tradition of serving in the armed forces and a daughter, Meghan, who is a presenter on ABC's "The View." His mother, Roberta, aged 106, is also still living.

For his military service, he was awarded the Silver Star, the Bronze Star, the Legion of Merit, a Purple Heart and the Distinguished Flying Cross.

He faced his final diagnosis with characteristic courage, telling CNN's Jake Tapper that "every life has to end one way or another."

Asked how he wanted to be remembered, McCain said: "He served his country, and not always right -- made a lot of mistakes, made a lot of errors -- but served his country, and, I hope we could add, honorably."

McCain, who will be remembered as much for his combative nature as his political achievements, summed up the meaning of a life forged in the example of his political hero Theodore Roosevelt when he stood before the flag-draped coffin of his friend and foe, Sen. Kennedy, in 2009, his late colleague from Massachusetts, who died from the same form of brain cancer that eventually killed McCain.

"Ted and I shared the sentiment that a fight not joined was a fight not enjoyed."