Reconnecting to a session
You can permit players to reconnect to a session they were in after their connection gets disrupted by using the FindFriendSession
function. This is often used to allow players to rejoin a game after their Internet drops or their game client crashes.
Note that the game server must not have unregistered them as a player in order for this technique to work. Refer to Unregister players for more detail on the requirements to support reconnections.
Checking if a session is available to reconnect to
You will most likely want to perform this check at the main menu of your game, and at the menu that a user is sent back to after a disconnection, so that you can offer them the option of reconnecting to the game.
- C++
- Blueprints
First, get the online session interface:
#include "OnlineSubsystem.h"
#include "OnlineSubsystemUtils.h"
#include "Interfaces/OnlineSessionInterface.h"
// ...
IOnlineSubsystem* Subsystem = Online::GetSubsystem(this->GetWorld());
IOnlineSessionPtr Session = Subsystem->GetSessionInterface();
Register the event handler so you know when you receive the search results. FindFriendSessionDelegateHandle
is declared as an FDelegateHandle
.
this->FindFriendSessionDelegateHandle =
Session->AddOnFindFriendSessionCompleteDelegate_Handle(
0 /* LocalUserNum */,
FOnFindFriendSessionComplete::FDelegate::CreateUObject(
this,
&UMyClass::HandleFindFriendSessionComplete));
Call FindFriendSession
, using the current user ID as the "friend ID" parameter:
if (!Session->FindFriendSession(0 /* LocalUserNum */, *UserId))
{
// Call didn't start, return error.
Session->ClearOnFindFriendSessionCompleteDelegate_Handle(0 /* LocalUserNum */, this->FindFriendSessionDelegateHandle);
}
When your callback fires, you can handle whether or not a session is available:
void UMyClass::HandleFindFriendSessionComplete(
int32 LocalUserNum,
bool bWasSuccessful,
const TArray<FOnlineSessionSearchResult> &Results)
{
// NOTE: bWasSuccessful is only true if the call succeeded *AND* a session was found.
// It's normal for it to be false when the call succeeds if the user doesn't have
// a session to reconnect to. You should not treat a false value as an indication to
// retry the request.
if (bWasSuccessful && Results.Num() > 0)
{
// The user has a session they can reconnect to. You can handle the (at most one)
// search result from the Results array the same way that search results
// are handled in "Finding a session".
Session->ClearOnFindFriendSessionCompleteDelegate_Handle(this->FindFriendSessionDelegateHandle);
this->FindFriendSessionDelegateHandle.Reset();
return;
}
// Otherwise, the user does not have a session to reconnect to.
Session->ClearOnFindFriendSessionCompleteDelegate_Handle(this->FindFriendSessionDelegateHandle);
this->FindFriendSessionDelegateHandle.Reset();
}
Refer to Connecting to a game server on how to use the search result to reconnect to the game server.