How To Use Sessions In C++

Features for the future

  • Example of network error handling. Like getting disconnected due to a server shutdown.
  • Example of getting information into UMG. Like the Serverlist.
  • Example of extending the GameSession class. Adding more information to your GameSession.
  • Example of extending several other classes that you can make your Session System unique and you will directly understand the ShooterGame after learning all of this.

What is this Tutorial about?

In this Tutorial, I'm going to show you a very basic Code to Create, Find, Join and Destroy Session in C++. So basically we are going to create the Blueprint Session Nodes.

Getting Started

Prepare your Project to use Sessions and OnlineSubsystems

So first of all, we need to get your Project ready to use all of this. I recommend you to start with an empty project, so you can first get an idea how this works, before trying to implement this into your already started project!

Changing the "DefaultEngine.ini"

You can find the "DefaultEngine.ini" file in the Config folder in your top most project folder. You will want to add the following line to it:
1
[OnlineSubsystem]
2
DefaultPlatformService=Null
Copied!

Changing the "YourProjectName.Build.cs"

You can find this file in your Project when you opened it with Visual Studio. You need to add "OnlineSubsystem", "OnlineSubsystemUtils" (for later usage) and the OnlineSubsystem NULL. It should look similar to this:
1
using UnrealBuildTool;
2
3
public class NetworkSessionTest : ModuleRules
4
{
5
public NetworkSessionTest(TargetInfo Target)
6
{
7
PublicDependencyModuleNames.AddRange(new string[] { "Core", "CoreUObject", "Engine", "InputCore", "OnlineSubsystem", "OnlineSubsystemUtils" });
8
9
DynamicallyLoadedModuleNames.Add("OnlineSubsystemNull");
10
}
11
}
Copied!

Changing the "YourProjectName.h"

This file can also be found in the Project when you open it with Visual Studio. You want to change
1
#include "EngineMinimal.h"
Copied!
to
1
#include "Engine.h".
Copied!
As well as add these two #includes under the "Engine.h" one.
1
#include "UnrealNetwork.h"
2
#include "Online.h"
Copied!
So your file looks something like this:
1
#ifndef __NETWORKSESSIONTEST_H__
2
#define __NETWORKSESSIONTEST_H__
3
4
#include "Engine.h"
5
#include "UnrealNetwork.h"
6
#include "Online.h"
7
#endif
Copied!
And that's it for setting up the Project!

My TestProject Setup

So, i want to let you know how my test project is setup and what i am using. I create a new fresh C++ Thirst Person Project and added ONE Class.
I made a child class of "UGameInstance" and called it "UNWGameInstance". (NW = Network). This is what i am referring to from now on and what you will read when seeing my function. Because every function for Creating, Finding,.. Sessions will be placed here.

Code to Create, Find, Join and Destroy Sessions

We are using a lot of Unreal Engine 4's functions here. All these functions are placed in an "SessionInterface" that is designed to handle sessions for different OnlineSubsystems. So although we are using "NULL" here, this should also work with Steam and other Subsystems. At least for the basics that all Subsystems share.
These functions all call a so called "delegate" once they are finished doing what they should do. All Session actions can take some time, so these functions are important. We will create 1-2 delegates, handles and functions for every one of these 4 Sessions operations. They will give us information like if the action was successful or not.

Terms you will read a lot about

Word/Term
Explanation
OnlineSubsystem
OnlineSubsystems are for example "Steam". But you can also use "NULL", which is simply the basic UE4 Subsystem. They all use so called "Wrapper"-Functions. They give us Friend Lists, Unique IDs or Master Server that allow us to find Servers over the Internet and not only on LAN!
Wrapper Functions
Wrapper Functions are something really cool that makes it easy for us to setup the Sessions for all different OnlineSubsystems. While we only need to call "CreateSession", this wrapper function will do the necessary steps to Create a Session in the active Subsystem. So we can create our logic without thinking about Steam or other Subsystems.
Session
A Session is not the Map or the Server itself. A Session is an invisible thing that a Server can Create and a Client can join. They will still need to join the specific Map after joining the Session. A Session is more like an entry in a Database that helps you keeping track of all running Servers.
Session Interface
That is nearly the same as the Session explained above. We will use the Interface instead of the Session itself, because it uses the Wrapper functions we need. We can always get this Internet if we have a valid OnlineSubsystem!

Creating a Session

Yes, let's start with creating a simple Session. I will always post the things we put into the Header file first and after that the logic will fill in with the .cpp File! This will all be placed in the UGameInstance Child class i have created. We don't need other classes.
So what do we need?
Creating a Session | Header File
First we need a function we can use to gather all the settings we want to use for our Session. Let's call this function "HostSession".
1
In our UNWGameInstance.h:
2
3
/**
4
* Function to host a game!
5
*
6
* @Param UserID User that started the request
7
* @Param SessionName Name of the Session
8
* @Param bIsLAN Is this is LAN Game?
9
* @Param bIsPresence "Is the Session to create a presence Session"
10
* @Param MaxNumPlayers Number of Maximum allowed players on this "Session" (Server)
11
*/
12
bool HostSession(TSharedPtr<const FUniqueNetId> UserId, FName SessionName, bool bIsLAN, bool bIsPresence, int32 MaxNumPlayers);
Copied!
The comments explain a lot already, so i will step back from explaining the parameters in the function declarations.
Now we also need the Delegates i talked about earlier. They are used by the "CreateSession" function of the SessionInterface to tell use when the process is done.
1
// In our UNWGameInstance.h:
2
3
/* Delegate called when session created */
4
FOnCreateSessionCompleteDelegate OnCreateSessionCompleteDelegate;
5
/* Delegate called when session started */
6
FOnStartSessionCompleteDelegate OnStartSessionCompleteDelegate;
7
8
/** Handles to registered delegates for creating/starting a session */
9
FDelegateHandle OnCreateSessionCompleteDelegateHandle;
10
FDelegateHandle OnStartSessionCompleteDelegateHandle;
Copied!
So we have a Delegate and a Handle for Creating and Starting a Session. Now we also need a variable we use for the Settings that our Session will have (like LAN or Number of allowed Players):
1
// In our UNWGameInstance.h:
2
3
TSharedPtr<class FOnlineSessionSettings> SessionSettings;
Copied!
And we will also add a Constructor to our GameInstance class, which is called when the Object is created. We need this to bind the functions to the delegates!
1
// In our UNWGameInstance.h
2
3
UNWGameInstance(const FObjectInitializer& ObjectInitializer);
Copied!
And finally, we need a function that we bind to the Delegate, so we can perform some actions once we know that the Creation process is complete:
1
// In our UNWGameInstance.h:
2
3
/**
4
* Function fired when a session create request has completed
5
*
6
* @param SessionName the name of the session this callback is for
7
* @param bWasSuccessful true if the async action completed without error, false if there was an error
8
*/
9
virtual void OnCreateSessionComplete(FName SessionName, bool bWasSuccessful);
10
11
/**
12
* Function fired when a session start request has completed
13
*
14
* @param SessionName the name of the session this callback is for
15
* @param bWasSuccessful true if the async action completed without error, false if there was an error
16
*/
17
void OnStartOnlineGameComplete(FName SessionName, bool bWasSuccessful);
Copied!
Again, the Comments explain the parameters. These function will have different values for their parameters depending on if the process was successful or not!
Creating a Session | CPP file
Now we fill these functions with logic.
First of all, we will bind the functions to the delegates in our Constructor:
1
// In our UNWGameIntance.cpp:
2
3
UNWGameInstance::UNWGameInstance(const FObjectInitializer& ObjectInitializer)
4
: Super(ObjectInitializer)
5
{
6
/** Bind function for CREATING a Session */
7
OnCreateSessionCompleteDelegate = FOnCreateSessionCompleteDelegate::CreateUObject(this, &UNWGameInstance::OnCreateSessionComplete);
8
OnStartSessionCompleteDelegate = FOnStartSessionCompleteDelegate::CreateUObject(this, &UNWGameInstance::OnStartOnlineGameComplete);
9
}
Copied!
All upcoming bindings for the other operations will be placed in this Constructor, under these two binds.
Now let's have a look at the "HostSession" function we created:
1
// In our UNWGameIntance.cpp:
2
3
bool UNWGameInstance::HostSession(TSharedPtr<const FUniqueNetId> UserId, FName SessionName, bool bIsLAN, bool bIsPresence, int32 MaxNumPlayers)
4
{
5
// Get the Online Subsystem to work with
6
IOnlineSubsystem* const OnlineSub = IOnlineSubsystem::Get();
7
8
if (OnlineSub)
9
{
10
// Get the Session Interface, so we can call the "CreateSession" function on it
11
IOnlineSessionPtr Sessions = OnlineSub->GetSessionInterface();
12
13
if (Sessions.IsValid() && UserId.IsValid())
14
{
15
/*
16
Fill in all the Session Settings that we want to use.
17
18
There are more with SessionSettings.Set(...);
19
For example the Map or the GameMode/Type.
20
*/
21
SessionSettings = MakeShareable(new FOnlineSessionSettings());
22
23
SessionSettings->bIsLANMatch = bIsLAN;
24
SessionSettings->bUsesPresence = bIsPresence;
25
SessionSettings->NumPublicConnections = MaxNumPlayers;
26
SessionSettings->NumPrivateConnections = 0;
27
SessionSettings->bAllowInvites = true;
28
SessionSettings->bAllowJoinInProgress = true;
29
SessionSettings->bShouldAdvertise = true;
30
SessionSettings->bAllowJoinViaPresence = true;
31
SessionSettings->bAllowJoinViaPresenceFriendsOnly = false;
32
33
SessionSettings->Set(SETTING_MAPNAME, FString("NewMap"), EOnlineDataAdvertisementType::ViaOnlineService);
34
35
// Set the delegate to the Handle of the SessionInterface
36
OnCreateSessionCompleteDelegateHandle = Sessions->AddOnCreateSessionCompleteDelegate_Handle(OnCreateSessionCompleteDelegate);
37
38
// Our delegate should get called when this is complete (doesn't need to be successful!)
39
return Sessions->CreateSession(*UserId, SessionName, *SessionSettings);
40
}
41
}
42
else
43
{
44
GEngine->AddOnScreenDebugMessage(-1, 10.f, FColor::Red, TEXT("No OnlineSubsytem found!"));
45
}
46
47
return false;
48
}
Copied!
Since i commented everything and this is VERY similar to the upcoming functions, i will only explain this once:
The first thing we do is getting our OnlineSubsystem, because we need the SessionInterface from it. Once we made sure that it is valid, we get the SessionInterface and make sure this and the UsedId are valid.
Then we set a lot of different SessionSettings, like Number of Players etc. After we did this, we going to setting the delegate of the "CreateSessionsComplete" handle to the one we create and that we bound a functions to. So we make sure, that this is the one getting used and called once the "CreateSession" process is finished. We will do this for every Session operation from now on, so i won't explain this again.
Once we did this, we are going to call the "CreateSession" function of the Session Interface and we are done. Now it could take some seconds until it is finished and the Engine calls our Delegate Functions, which we will fill with logic now:
1
// In our UNWGameIntance.cpp:
2
3
void UNWGameInstance::OnCreateSessionComplete(FName SessionName, bool bWasSuccessful)
4
{
5
GEngine->AddOnScreenDebugMessage(-1, 10.f, FColor::Red, FString::Printf(TEXT("OnCreateSessionComplete %s, %d"), *SessionName.ToString(), bWasSuccessful));
6
7
// Get the OnlineSubsystem so we can get the Session Interface
8
IOnlineSubsystem* OnlineSub = IOnlineSubsystem::Get();
9
if (OnlineSub)
10
{
11
// Get the Session Interface to call the StartSession function
12
IOnlineSessionPtr Sessions = OnlineSub->GetSessionInterface();
13
14
if (Sessions.IsValid())
15
{
16
// Clear the SessionComplete delegate handle, since we finished this call
17
Sessions->ClearOnCreateSessionCompleteDelegate_Handle(OnCreateSessionCompleteDelegateHandle);
18
if (bWasSuccessful)
19
{
20
// Set the StartSession delegate handle
21
OnStartSessionCompleteDelegateHandle = Sessions->AddOnStartSessionCompleteDelegate_Handle(OnStartSessionCompleteDelegate);
22
23
// Our StartSessionComplete delegate should get called after this
24
Sessions->StartSession(SessionName);
25
}
26
}
27
28
}
29
}
Copied!
Here again, we will get the OnlineSubsystem and the SessionInterface. This will, again, repeat a lot of times now. Once we made sure that the SessionInterface is valid, we clear the Delegate from the handle, because the call is finished and we want to bind it next time we call "CreateSession". That's why we need to clear it.
After that, we can check if the process was "Successful". If yes, we set the Delegate of the "StartSessionComplete" handle and call the "StartSession" function with the "SessionName" we got. This is already the new Session we created!
This will also take an amount of time but once it is finished, the Engine calls the second Delegate function we created:
1
// In our UNWGameIntance.cpp:
2
3
void UNWGameInstance::OnStartOnlineGameComplete(FName SessionName, bool bWasSuccessful)
4
{
5
GEngine->AddOnScreenDebugMessage(-1, 10.f, FColor::Red, FString::Printf(TEXT("OnStartSessionComplete %s, %d"), *SessionName.ToString(), bWasSuccessful));
6
7
// Get the Online Subsystem so we can get the Session Interface
8
IOnlineSubsystem* OnlineSub = IOnlineSubsystem::Get();
9
if (OnlineSub)
10
{
11
// Get the Session Interface to clear the Delegate
12
IOnlineSessionPtr Sessions = OnlineSub->GetSessionInterface();
13
if (Sessions.IsValid())
14
{
15
// Clear the delegate, since we are done with this call
16
Sessions->ClearOnStartSessionCompleteDelegate_Handle(OnStartSessionCompleteDelegateHandle);
17
}
18
}
19
20
// If the start was successful, we can open a NewMap if we want. Make sure to use "listen" as a parameter!
21
if (bWasSuccessful)
22
{
23
UGameplayStatics::OpenLevel(GetWorld(), "NewMap", true, "listen");
24
}
25
}
Copied!
Similar to the first one, we get, check and clear things. Then, if everything is done and the process was again successful, we open a new Level with "listen" as a parameter. This is important!
And that's it. Now we created a Session and started it, so we are ready to get Clients on our Server/Session. But for that we need them to find our Session. So next up is "Finding Sessions".

Searching and Finding a Session

So, once we are sure that somewhere we have a Session we can find, we can proceed with the following code.
Searching and Finding a Session | Header File
Function to setup our search and start the searching:
1
// In our UNWGameInstance.h:
2
3
/**
4
* Find an online session
5
*
6
* @param UserId user that initiated the request
7
* @param bIsLAN are we searching LAN matches
8
* @param bIsPresence are we searching presence sessions
9
*/
10
void FindSessions(TSharedPtr<const FUniqueNetId> UserId, bool bIsLAN, bool bIsPresence);
Copied!
A delegate and a handle for it:
1
// In our UNWGameInstance.h:
2
3
/** Delegate for searching for sessions */
4
FOnFindSessionsCompleteDelegate OnFindSessionsCompleteDelegate;
5
6
/** Handle to registered delegate for searching a session */
7
FDelegateHandle OnFindSessionsCompleteDelegateHandle;
Copied!
A variable for our SearchSettings which will also contain our SearchResults, once this search is complete and successful:
1
// In our UNWGameInstance.h:
2
3
TSharedPtr<class FOnlineSessionSearch> SessionSearch;
Copied!
And finally the function we want to bind to the delegate:
1
// In our UNWGameInstance.h:
2
3
/**
4
* Delegate fired when a session search query has completed
5
*
6
* @param bWasSuccessful true if the async action completed without error, false if there was an error
7
*/
8
void OnFindSessionsComplete(bool bWasSuccessful);
Copied!
Searching and Finding a Session | CPP File
Now filling this with logic similar to the creation process:
1
// In our UNWGameInstance.cpp:
2
3
void UNWGameInstance::FindSessions(TSharedPtr<const FUniqueNetId> UserId, bool bIsLAN, bool bIsPresence)
4
{
5
// Get the OnlineSubsystem we want to work with
6
IOnlineSubsystem* OnlineSub = IOnlineSubsystem::Get();
7
8
if (OnlineSub)
9
{
10
// Get the SessionInterface from our OnlineSubsystem
11
IOnlineSessionPtr Sessions = OnlineSub->GetSessionInterface();
12
13
if (Sessions.IsValid() && UserId.IsValid())
14
{
15
/*
16
Fill in all the SearchSettings, like if we are searching for a LAN game and how many results we want to have!
17
*/
18
SessionSearch = MakeShareable(new FOnlineSessionSearch());
19
20
SessionSearch->bIsLanQuery = bIsLAN;
21
SessionSearch->MaxSearchResults = 20;
22
SessionSearch->PingBucketSize = 50;
23
24
// We only want to set this Query Setting if "bIsPresence" is true
25
if (bIsPresence)
26
{
27
SessionSearch->QuerySettings.Set(SEARCH_PRESENCE, bIsPresence, EOnlineComparisonOp::Equals);
28
}
29
30
TSharedRef<FOnlineSessionSearch> SearchSettingsRef = SessionSearch.ToSharedRef();
31
32
// Set the Delegate to the Delegate Handle of the FindSession function
33
OnFindSessionsCompleteDelegateHandle = Sessions->AddOnFindSessionsCompleteDelegate_Handle(OnFindSessionsCompleteDelegate);
34
35
// Finally call the SessionInterface function. The Delegate gets called once this is finished
36
Sessions->FindSessions(*UserId, SearchSettingsRef);
37
}
38
}
39
else
40
{
41
// If something goes wrong, just call the Delegate Function directly with "false".
42
OnFindSessionsComplete(false);
43
}
44
}
Copied!
Getting OnlineSubsystem etc and filling the SearchSettings variable. Then setting the Delegate to the handle and tell the SessionInterface to "FindSessions". That's all (:
Once this is finished, the Delegate functions is called. We still need to connect these in the Constructor:
1
// In our UNWGameInstance.cpp:
2
3
/** Bind function for FINDING a Session */
4
OnFindSessionsCompleteDelegate = FOnFindSessionsCompleteDelegate::CreateUObject(this, &UNWGameInstance::OnFindSessionsComplete);
Copied!
And the function logic:
1
// In our UNWGameInstance.cpp:
2
3
void UNWGameInstance::OnFindSessionsComplete(bool bWasSuccessful)
4
{
5
GEngine->AddOnScreenDebugMessage(-1, 10.f, FColor::Red, FString::Printf(TEXT("OFindSessionsComplete bSuccess: %d"), bWasSuccessful));
6
7
// Get OnlineSubsystem we want to work with
8
IOnlineSubsystem* const OnlineSub = IOnlineSubsystem::Get();
9
if (OnlineSub)
10
{
11
// Get SessionInterface of the OnlineSubsystem
12
IOnlineSessionPtr Sessions = OnlineSub->GetSessionInterface();
13
if (Sessions.IsValid())
14
{
15
// Clear the Delegate handle, since we finished this call
16
Sessions->ClearOnFindSessionsCompleteDelegate_Handle(OnFindSessionsCompleteDelegateHandle);
17
18
// Just debugging the Number of Search results. Can be displayed in UMG or something later on
19
GEngine->AddOnScreenDebugMessage(-1, 10.f, FColor::Red, FString::Printf(TEXT("Num Search Results: %d"), SessionSearch->SearchResults.Num()));
20
21
// If we have found at least 1 session, we just going to debug them. You could add them to a list of UMG Widgets, like it is done in the BP version!
22
if (SessionSearch->SearchResults.Num() > 0)
23
{
24
// "SessionSearch->SearchResults" is an Array that contains all the information. You can access the Session in this and get a lot of information.
25
// This can be customized later on with your own classes to add more information that can be set and displayed
26
for (int32 SearchIdx = 0; SearchIdx < SessionSearch->SearchResults.Num(); SearchIdx++)
27
{
28
// OwningUserName is just the SessionName for now. I guess you can create your own Host Settings class and GameSession Class and add a proper GameServer Name here.
29
// This is something you can't do in Blueprint for example!
30
GEngine->AddOnScreenDebugMessage(-1, 10.f, FColor::Red, FString::Printf(TEXT("Session Number: %d | Sessionname: %s "), SearchIdx+1, *(SessionSearch->SearchResults[SearchIdx].Session.OwningUserName)));
31
}
32
}
33
}
34
}
35
}
Copied!
After getting the OnlineSubsystem and the SessionInterface, we clear the DelegateHandle again and now we can work with the SearchResults. They are stored in the "SessionSearch" variable we created. "SessionSearch->SearchResults" is an array with all found Sessions. You can get several information from this and later on maybe create your own child class of this to add more information! I'm just printing them to the Screen.
That's all for finding Sessions. Now we can go on and try to join one.

Joining a Session

There are different ways you can Join a session, but we will just use a Session result which we can get from the SearchResult array and joined it with help of the SessionInterface. As easy as possible.
Joining a Session | Header file
So the function we are going to use:
1
// In our UNWGameInstance.h:
2
3
/**
4
* Joins a session via a search result
5
*
6
* @param SessionName name of session
7
* @param SearchResult Session to join
8
*
9
* @return bool true if successful, false otherwise
10
*/
11
bool JoinSession(TSharedPtr<const FUniqueNetId> UserId, FName SessionName, const FOnlineSessionSearchResult& SearchResult);
Copied!
The delegates and the function that we bind to it:
1
// In our UNWGameInstance.h:
2
3
/** Delegate for joining a session */
4
FOnJoinSessionCompleteDelegate OnJoinSessionCompleteDelegate;
5
6
/** Handle to registered delegate for joining a session */
7
FDelegateHandle OnJoinSessionCompleteDelegateHandle;
Copied!
1
// In our UNWGameInstance.h:
2
3
/**
4
* Delegate fired when a session join request has completed
5
*
6
* @param SessionName the name of the session this callback is for
7
* @param bWasSuccessful true if the async action completed without error, false if there was an error
8
*/
9
void OnJoinSessionComplete(FName SessionName, EOnJoinSessionCompleteResult::Type Result);
Copied!
Nothing fancy as Settings here. Just the functions and the delegates.
Joining a Session | CPP file
1
// In our UNWGameInstance.cpp:
2
3
bool UNWGameInstance::JoinSession(TSharedPtr<const FUniqueNetId> UserId, FName SessionName, const FOnlineSessionSearchResult& SearchResult)
4
{
5
// Return bool
6
bool bSuccessful = false;
7
8
// Get OnlineSubsystem we want to work with
9
IOnlineSubsystem* OnlineSub = IOnlineSubsystem::Get();
10
11
if (OnlineSub)
12
{
13
// Get SessionInterface from the OnlineSubsystem
14
IOnlineSessionPtr Sessions = OnlineSub->GetSessionInterface();
15
16
if (Sessions.IsValid() && UserId.IsValid())
17
{
18
// Set the Handle again
19
OnJoinSessionCompleteDelegateHandle = Sessions->AddOnJoinSessionCompleteDelegate_Handle(OnJoinSessionCompleteDelegate);
20
21
// Call the "JoinSession" Function with the passed "SearchResult". The "SessionSearch->SearchResults" can be used to get such a
22
// "FOnlineSessionSearchResult" and pass it. Pretty straight forward!
23
bSuccessful = Sessions->JoinSession(*UserId, SessionName, SearchResult);
24
}
25
}
26
27
return bSuccessful;
28
}
Copied!
We are doing nothing new here. Since we have no settings, we are not filling any. We are just taking the SearchResult that was passed and call "JoinSession" once we set the delegate to the handle.
And once this is finished, our function gets called again. Again, don't forget to bind it in the constructor:
1
// In our UNWGameInstance.cpp:
2
3
/** Bind function for JOINING a Session */
4
OnJoinSessionCompleteDelegate = FOnJoinSessionCompleteDelegate::CreateUObject(this, &UNWGameInstance::OnJoinSessionComplete);
Copied!
1
// In our UNWGameInstance.cpp:
2
3
void UNWGameInstance::OnJoinSessionComplete(FName SessionName, EOnJoinSessionCompleteResult::Type Result)
4
{
5
GEngine->AddOnScreenDebugMessage(-1, 10.f, FColor::Red, FString::Printf(TEXT("OnJoinSessionComplete %s, %d"), *SessionName.ToString(), static_cast<int32>(Result)));
6
7
// Get the OnlineSubsystem we want to work with
8
IOnlineSubsystem* OnlineSub = IOnlineSubsystem::Get();
9
if (OnlineSub)
10
{
11
// Get SessionInterface from the OnlineSubsystem
12
IOnlineSessionPtr Sessions = OnlineSub->GetSessionInterface();
13
14
if (Sessions.IsValid())
15
{
16
// Clear the Delegate again
17
Sessions->ClearOnJoinSessionCompleteDelegate_Handle(OnJoinSessionCompleteDelegateHandle);
18
19
// Get the first local PlayerController, so we can call "ClientTravel" to get to the Server Map
20
// This is something the Blueprint Node "Join Session" does automatically!
21
APlayerController * const PlayerController = GetFirstLocalPlayerController();
22
23
// We need a FString to use ClientTravel and we can let the SessionInterface contruct such a
24
// String for us by giving him the SessionName and an empty String. We want to do this, because
25
// Every OnlineSubsystem uses different TravelURLs
26
FString TravelURL;
27
28
if (PlayerController && Sessions->GetResolvedConnectString(SessionName, TravelURL))
29
{
30
// Finally call the ClienTravel. If you want, you could print the TravelURL to see
31
// how it really looks like
32
PlayerController->ClientTravel(TravelURL, ETravelType::TRAVEL_Absolute);
33
}
34
}
35
}
36
}
Copied!
Here we are doing something new. After getting the OnlineSubsystem and the SessionInterface, we clear the handle. Then we get the PlayerController of the joining Player. Since we are still on this Player, we can just get the FirstLocal one.
The we create an FString that will hold the TravelURL, which we need for a ClientTravel to the Map of the Server. How do we get the TravelURL? Easy: We tell the SessionInterface to create us one. Just pass the SessionName (which at this point is already the one of the Session we joined!) and the FString. Then we can call the ClientTravel function of the PlayerController and we are on the ServerMap, ready to play!
But now we need to also be able to destroy a Session. This is important, because Sessions take Slots on Servers and prevent us from creating new ones or join others as long as they exist.

Destroying a Session

Destroying a Session doesn't need an extra function from us, since we don't need settings or something like that. So we only need the delegate, handle and delegate function:
Destroying a Session | Header file
1
// In our UNWGameInstance.h:
2
3
/** Delegate for destroying a session */
4
FOnDestroySessionCompleteDelegate OnDestroySessionCompleteDelegate;
5
6
/** Handle to registered delegate for destroying a session */
7
FDelegateHandle OnDestroySessionCompleteDelegateHandle;
Copied!
1
// In our UNWGameInstance.h:
2
3
/**
4
* Delegate fired when a destroying an online session has completed
5
*
6
* @param SessionName the name of the session this callback is for
7
* @param bWasSuccessful true if the async action completed without error, false if there was an error
8
*/
9
virtual void OnDestroySessionComplete(FName SessionName, bool bWasSuccessful);
Copied!
Destroying a Session | CPP file
Binding the function in the Constructor!
1
// In our UNWGameInstance.cpp:
2
3
/** Bind function for DESTROYING a Session */
4
OnDestroySessionCompleteDelegate = FOnDestroySessionCompleteDelegate::CreateUObject(this, &UNWGameInstance::OnDestroySessionComplete);
Copied!
And filling the function with logic:
1
// In our UNWGameInstance.cpp:
2
3
void UNWGameInstance::OnDestroySessionComplete(FName SessionName, bool bWasSuccessful)
4
{
5
GEngine->AddOnScreenDebugMessage(-1, 10.f, FColor::Red, FString::Printf(TEXT("OnDestroySessionComplete %s, %d"), *SessionName.ToString(), bWasSuccessful));
6
7
// Get the OnlineSubsystem we want to work with
8
IOnlineSubsystem* OnlineSub = IOnlineSubsystem::Get();
9
if (OnlineSub)
10
{
11
// Get the SessionInterface from the OnlineSubsystem
12
IOnlineSessionPtr Sessions = OnlineSub->GetSessionInterface();
13
14
if (Sessions.IsValid())
15
{
16
// Clear the Delegate
17
Sessions->ClearOnDestroySessionCompleteDelegate_Handle(OnDestroySessionCompleteDelegateHandle);
18
19
// If it was successful, we just load another level (could be a MainMenu!)
20
if (bWasSuccessful)
21
{
22
UGameplayStatics::OpenLevel(GetWorld(), "ThirdPersonExampleMap", true);
23
}
24
}
25
}
26
}
Copied!
Doing the same with the OnlineSubsystem and the SessionInterface again and once the destruction was successful, we Open the start level again, which could be the MainMenu for example.
And that's it, this is all you need for a basic setup. You can now create Widgets or so that can use these functions, BUT you can't make these functions BlueprintCallable. You need a second function for each process that is BlueprintCallable.

BlueprintCallable Functions to test this Setup

Creating a Session

1
// In our UNWGameInstance.h:
2
3
UFUNCTION(BlueprintCallable, Category = "Network|Test")
4
void StartOnlineGame();
Copied!
1
// In our UNWGameInstance.cpp:
2
3
void UNWGameInstance::StartOnlineGame()
4
{
5
// Creating a local player where we can get the UserID from
6
ULocalPlayer* const Player = GetFirstGamePlayer();
7
8
// Call our custom HostSession function. GameSessionName is a GameInstance variable
9
HostSession(Player->GetPreferredUniqueNetId(), GameSessionName, true, true, 4);
10
}
Copied!

Searching and Finding a Session

1
// In our UNWGameInstance.h:
2
3
UFUNCTION(BlueprintCallable, Category = "Network|Test")
4
void FindOnlineGames();
Copied!
1
// In our UNWGameInstance.cpp:
2
3
void UNWGameInstance::FindOnlineGames()
4
{
5
ULocalPlayer* const Player = GetFirstGamePlayer();
6
7
FindSessions(Player->GetPreferredUniqueNetId(), true, true);
8
}
Copied!

Joining a Session

1
// In our UNWGameInstance.h:
2
3
UFUNCTION(BlueprintCallable, Category = "Network|Test")
4
void JoinOnlineGame();
Copied!
1
// In our UNWGameInstance.cpp:
2
3
void UNWGameInstance::JoinOnlineGame()
4
{
5
ULocalPlayer* const Player = GetFirstGamePlayer();
6
7
// Just a SearchResult where we can save the one we want to use, for the case we find more than one!
8
FOnlineSessionSearchResult SearchResult;
9
10
// If the Array is not empty, we can go through it
11
if (SessionSearch->SearchResults.Num() > 0)
12
{
13
for (int32 i = 0; i < SessionSearch->SearchResults.Num(); i++)
14
{
15
// To avoid something crazy, we filter sessions from ourself
16
if (SessionSearch->SearchResults[i].Session.OwningUserId != Player->GetPreferredUniqueNetId())
17
{
18
SearchResult = SessionSearch->SearchResults[i];
19
20
// Once we found sounce a Session that is not ours, just join it. Instead of using a for loop, you could
21
// use a widget where you click on and have a reference for the GameSession it represents which you can use
22
// here
23
JoinSession(Player->GetPreferredUniqueNetId(), GameSessionName, SearchResult);
24
break;
25
}
26
}
27
}
28
}
Copied!

Destroying a Session

1
// In our UNWGameInstance.h:
2
3
UFUNCTION(BlueprintCallable, Category = "Network|Test")
4
void DestroySessionAndLeaveGame();
Copied!
1
// In our UNWGameInstance.cpp:
2
3
void UNWGameInstance::DestroySessionAndLeaveGame()
4
{
5
IOnlineSubsystem* OnlineSub = IOnlineSubsystem::Get();
6
if (OnlineSub)
7
{
8
IOnlineSessionPtr Sessions = OnlineSub->GetSessionInterface();
9
10
if (Sessions.IsValid())
11
{
12
Sessions->AddOnDestroySessionCompleteDelegate_Handle(OnDestroySessionCompleteDelegate);
13
14
Sessions->DestroySession(GameSessionName);
15
}
16
}
17
}
Copied!