Connecting to a game server
Once you retrieve the connection URL and join the session, you'll need to open a connection to the multiplayer server.
Connecting to the game server
- C++
- Blueprints
To connect to a game server, use the GEngine->Browse
function. This assumes that you have the ConnectInfo
variable populated with the connection string, as demonstrated in Finding a session:
if (GEngine != nullptr)
{
FURL NewURL(nullptr, *ConnectInfo, ETravelType::TRAVEL_Absolute);
FString BrowseError;
if (GEngine->Browse(GEngine->GetWorldContextFromWorldChecked(this->GetWorld()), NewURL, BrowseError) ==
EBrowseReturnVal::Failure)
{
UE_LOG(LogTemp, Error, TEXT("Failed to start browse: %s"), *BrowseError);
}
}
If the connection fails asynchronously, for example by timing out when connecting to the game server, the error will be sent to the "Network Error" and "Travel Error" events on your Game Instance.
These events are accessible in both C++ and blueprints (without Online Subsystem Blueprints). You should always handle these events if you're building a multiplayer game:
Disconnecting from a game server
If you're disconnecting from a game server and going back to a single player map (such as the main menu), you can just use the "Open Level" blueprint node:
Performing "server travel" from the server
Your game server might want to bring the currently connected players to a new map. This is called "server travel", because the server is the one initiating the travel to a new map.
It is highly recommended that you use seamless travel for travelling to new maps in packaged games. Non-seamless travel is not well maintained by Epic Games, and is broken in Unreal Engine 5.0.
Turning on seamless travel
- C++
- Blueprints
First, make sure you have seamless travel enabled in your game mode. This must be done on the server:
AGameModeBase *GameModeBase = WorldContextObject->GetWorld()->GetAuthGameMode<AGameModeBase>();
if (IsValid(GameModeBase))
{
GameModeBase->bUseSeamlessTravel = true;
}
Travelling to the new map
- C++
- Blueprints
On the server, call the ServerTravel
function on the current world with the new map name:
this->GetWorld()->ServerTravel(TEXT("/Game/MyNewMap"), true);