Barely hopeful asylum seekers clung to a border fence that Hungarian agents closed just after midnight Tuesday as European nations deployed police, soldiers and, here, a razor-wire-covered boxcar in a bid to stem the torrent of refugees and migrants flowing across Europe.

The crossing here closed, reopened, then closed again in the middle of the night. Hungary has said it will seal off its border with Serbia on Tuesday to prevent refugees and migrants from entering the country, but a Hungarian police officer here said the frontier would reopen in the morning.

“The border is closed and it won’t open, and there’s nothing we can do,” he told a volunteer. But he said a very small number of people would be allowed in Tuesday. That could not be confirmed.

Tens of thousands of men, women and children have been racing to reach Western Europe before their path is blocked, and on Monday several nations declared that they could no longer hold to the European Union ideal of open internal borders.

Restrictions swept across Europe from west to east Monday. But none matched Hungary in scope or ambition, where Prime Minister Viktor Orban swore in 860 new border police at a ­ceremony in Budapest’s Heroes’ Square.

“You are the defenders of our culture, lifestyle and sovereignty,” Orban told them.

By late Monday, Hungarian agents had sealed one of the last gaps in their 108-mile fence on the border with Serbia by rolling into place a boxcar with seven strings of razor wire attached, a sharp warning for asylum seekers to turn elsewhere.

The new restrictions pushed asylum seekers to try even harder to reach Germany and other Western European nations before it was too late. Germany has thrown open its doors, converting gymnasiums, airport terminals and office buildings into temporary shelter for as many as 1 million new arrivals this year alone.

But as even Germany began to impose border controls Monday, leading Austria to do the same, migrants raced to beat the clampdowns.

“We don’t know how long countries will take us in. So we had to work fast,” said Mohammed Hayek, 26, a graphic designer from Syria who arrived Sunday in Budapest bound for Germany.

Farther up the migrant route at the border between Serbia and Hungary, others worried that they had missed their window. In the dark and the drizzle, many said that they had hurried from Syria in an attempt to beat the clock, shaving three days off what is often a 12-day journey.

“I’m really down. If we can’t get to Germany, I have no hope. The dream is off,” said Bilal Rahmani, 18, who was sitting glumly on an embankment Monday night on the chaotic Serbian side of the border, where more than 500 people lined up to speak to Hungarian border agents. Rahmani was traveling with his family from Damascus and said that they had not known the border would be closed.

After police shut down the border, groups of refugees from the Middle East and Africa huddled in groups, pleaded with police — to no avail — and prayed. Mohammad Baqer, 18, showed up 20 minutes after the closing. He hadn’t slept all night, taking buses and walking all day only to arrive in Horgos too late.

“Now I need a new plan,” Baqer said. “When I learned this news, I felt very bad. But I think more of my people, of people in Afghanistan and in Syria back home, who now don’t really have a choice.”

New laws going into effect in Hungary on Tuesday threaten up to three years in prison for unauthorized passage into the country. Under the new rules, most asylum seekers can be turned away, since nearly all are coming from Serbia, which theoretically could provide them with shelter. As migrants await Hungary’s asylum decision, they will be held in makeshift camps set up along the border, where many refugee advocates fear conditions will be squalid. Authorities closed a strip of airspace along the border to make it easier to patrol using helicopters and other aircraft.

In the wave of constricted travel across Europe on Monday, Germany dispatched border guards to its border with Austria, which in turn scrambled troops to the border with Hungary. Slovakia imposed tough frontier checks, and Poland and the Czech Republic said they were ready to follow suit. Farther north, the Netherlands tightened controls on traffic coming from Germany.

The moves were a sharp reversal of the open-frontier policy that has become a hallmark of E.U. integration.

At Vienna’s central train stations, crowds of refugees swelled by the hour as new migrants were bused in from the Hungarian border and rail service on to Germany slowed to a crawl, with one Munich-bound train after another canceled.

More and more police arrived and appealed for calm there and at other stations, careful not to panic the migrants, promising they would soon be moving to their goal, Germany.

But the refugees could read the text messages on their cellphones and see from the train departure board that the once free-and-easy travel in Central Europe was contracting and that bottlenecks were forming along old borders.

“I want to reach Germany,” Samir, 38, a Syrian businessman from Aleppo, said as his family of five waited at the Westbahnhof station in Vienna. He complained of chaos at the station, which has been transformed into a temporary refugee camp, patrolled by large numbers of police and with doctors staffing makeshift clinics and volunteers serving hot meals.

“I don’t want any financial assistance. I will start a business. We have some resources,” said Samir, who would not give his last name because he was concerned about the safety of family members who remained in Syria.

Even Germany, which has declared that there are few limits to the number of asylum seekers it can accommodate, is increasingly under strain, with fresh records of new arrivals set nearly every day.

“Germany is strong and can do a lot,” German Vice Chancellor Sigmar Gabriel said in an open letter to supporters. “Nevertheless, in recent days we have seen that despite the best intentions, our reception capabilities have reached their limits, above all when it comes to the speed of the influx of refugees.”

He said that he believed that Germany would take in 1 million asylum seekers in 2015, an increase of 200,000 from previous estimates.

The proposal to parcel asylum seekers among 22 nations has come under heavy criticism from Central and Eastern European countries, which oppose any steps that would require mandatory refugee quotas.

A meeting of E.U. interior ministers ended Monday in discord, with officials able to agree on measures to strengthen Europe’s borders but not on efforts to redistribute 120,000 people across the European Union. Leaders agreed to keep talking and to revisit the matter early next month.

“To say ‘Let’s shut all the borders and keep everybody out’ is unrealistic, populistic and simply impossible,” said Frans Timmermans, vice president of the European Commission. “To say, ‘Let’s open all the borders and let everybody in’ is equally unrealistic because it would seriously harm the European social model.”

About 34,000 asylum seekers who received commitments from European countries in July will begin to disperse to their respective nations. But the efforts fall far short of the need because that number represents just a few days’ worth of arrivals. Hungarian border police say that more than 5,800 asylum seekers arrived Sunday. Hungary is so opposed to the influx that leaders there have worked to thwart any new deal, even though it would relieve pressure on them by redistributing people to other nations.

Birnbaum reported from Brussels. William Booth and Souad Mekhennet in Vienna, Anthony Faiola and Stephanie Kirchner in Berlin, Gergo Saling in Horgos, and Griff Witte in London contributed to this report.

Read more:

Germany’s enthusiasm for refugees might not last. These maps explain why.

Five reasons Germany reintroduced border controls

Read The Post’s coverage on the global surge in migration