# How to correctly create session with C++ 

**URL:** <https://forums.unrealengine.com/t/how-to-correctly-create-session-with-c/2304807>\
**Category:** Multiplayer & Networking\
**Tags:** unreal-engine, CPP, question\
**Created:** [January 26, 2025, 9:15pm UTC](https://forums.unrealengine.com/t/how-to-correctly-create-session-with-c/2304807 "2025-01-26T21:15:20Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![KKJMJ9](https://d3kjluh73b9h9o.cloudfront.net/original/4X/2/8/5/28502927f1d97ba1051b3b47ccfe17233bf41ef0.png) [@KKJMJ9](https://forums.unrealengine.com/u/KKJMJ9)\
**Post date:** [January 26, 2025, 9:15pm UTC](https://forums.unrealengine.com/t/how-to-correctly-create-session-with-c/2304807/1 "2025-01-26T21:15:20Z")

</div>

HI I’m trying to create session and join it using cpp, but i can’t join session that i created. When i create the session with blueprints and then join it with c++ it’s working fine, but when i create session with cpp using cpp a cannot join it and using blueprints it’s print “hello” but doesnt change level and I’m getting to output log messages: LogNet: Initial Connect Diagnostics: Sent ‘9’ packets in last ‘10.017827’ seconds, no packets received yet.  
LogNet: Initial Connect Diagnostics: Sent ‘10’ packets in last ‘10.000829’ seconds, no packets received yet.

Thanks for any replyes

cpp code:

```auto
// Fill out your copyright notice in the Description page of Project Settings.

#include "MultiplayerWidget.h"

bool UMultiplayerWidget::Initialize()
{
	Super::Initialize();
	
	//ServerIPTbx->OnTextChanged.AddDynamic(this, &UMultiplayerWidget::GetMaxPlayers); //Přidává funkci GetMaxPlayers do callu OnTextChanged

	HostGameBtn->OnClicked.AddDynamic(this, &UMultiplayerWidget::CreateSession); //Přidává funkci CreateSession do callu OnClicked
	JoinGameBtn->OnClicked.AddDynamic(this, &UMultiplayerWidget::FindJoinSession); //Přidává funkci FindJoinSession do callu OnClicked
	//DestroySessionButton->OnClicked.AddDynamic(this, &UMultiplayerWidget::DestroySession); //Přidává funkci FindJoinSession do callu OnClicked

	if (InputComponent) {
		InputComponent->BindAction("QuitAction", EInputEvent::IE_Pressed, this, &UMultiplayerWidget::QuitGame);
	}

	return true;
}

//Vytvoří session snad :(
void UMultiplayerWidget::CreateSession()
{
	UE_LOG(LogTemp, Warning, TEXT("Creating session")); //vypisuje do konzole Creating session

	UWidgetLayoutLibrary::RemoveAllWidgets(GetWorld());

	GetWorld()->GetFirstPlayerController()->bShowMouseCursor = false;

	IOnlineSubsystem* OnlineSubsystem = IOnlineSubsystem::Get(); // získá subsystem

	if (OnlineSubsystem) //Kontroluje zda se získal subsystem
	{
		IOnlineSessionPtr SessionPtrRef = OnlineSubsystem->GetSessionInterface(); //Získá rozhraní subsystému
		if (SessionPtrRef) 
		{
			FOnlineSessionSettings SessionInfo; //settings pro session
			SessionInfo.bIsLANMatch = true;
			SessionInfo.NumPublicConnections = 4;
			SessionInfo.bUsesPresence = false;
			SessionInfo.bShouldAdvertise = true;
			//SessionInfo.Set(TEXT("SEARCH_SESSION"), FString("Test"), EOnlineDataAdvertisementType::ViaOnlineService);

			SessionPtrRef->OnCreateSessionCompleteDelegates.AddUObject(this, &UMultiplayerWidget::OnCreatedSessionCompleted); //nastavení, že po dkončení vytváření session se spustí funce created s hodnotou true||false podle toho zda se session vytvořila úspěšně
			UE_LOG(LogTemp, Warning, TEXT("creating session v2"));
			SessionPtrRef->CreateSession(0, FName("MainSession"), SessionInfo);
		}
	}
}

//Kontrolní funkce zda se vytvořila session nebo ne
void UMultiplayerWidget::OnCreatedSessionCompleted(FName sessionName, bool succesful) {

	if (succesful) {
		UGameplayStatics::OpenLevel(GetWorld(), FName("MainMap"), true, TEXT("?listen"));
	}
	else {
		FString sessionNamestring = sessionName.ToString();
		UE_LOG(LogTemp, Error, TEXT("Session: %s, failed to create"), *sessionNamestring); //vypisuje do konzole zda se session vytvořila či ne
	}
}
//Získá číslo z EditableTextBox_369, to se poté použije jako maximální hranice pro hráčů na session
void UMultiplayerWidget::GetMaxPlayers(const FText& ftext)
{
	FString text = ftext.ToString(); //FText na FString
	maxPlayers = FCString::Atoi(*text); //Convert FString na int
}

void UMultiplayerWidget::QuitGame()
{
	DestroySession();
	UKismetSystemLibrary::QuitGame(GetWorld(), GetWorld()->GetFirstPlayerController(), EQuitPreference::Quit, true);
}

//Najidí a připojení se k session
void UMultiplayerWidget::FindJoinSession() {

	UWidgetLayoutLibrary::RemoveAllWidgets(GetWorld());

	GetWorld()->GetFirstPlayerController()->bShowMouseCursor = false;

	IOnlineSubsystem* OnlineSubsystem = IOnlineSubsystem::Get(); // získá subsystem

	if (OnlineSubsystem) //Kontroluje zda se získal subsystem
	{
		IOnlineSessionPtr SessionPtrRef = OnlineSubsystem->GetSessionInterface(); //Získá rozhraní subsystému
		if (SessionPtrRef)	//Kontroluje zda se získal rozhraní
		{
			sessionSearch = MakeShareable(new FOnlineSessionSearch());
			sessionSearch->MaxSearchResults = 100;
			sessionSearch->PingBucketSize = 50;
			sessionSearch->bIsLanQuery = true;

			UE_LOG(LogTemp, Warning, TEXT("Finding session"));

			SessionPtrRef->OnFindSessionsCompleteDelegates.AddUObject(this, &UMultiplayerWidget::OnFindSessionCompleted);

			SessionPtrRef->FindSessions(0, sessionSearch.ToSharedRef());
		}
	}
}
void UMultiplayerWidget::OnFindSessionCompleted(bool bWasSuccessful) {
	if (bWasSuccessful && sessionSearch.IsValid() && sessionSearch->SearchResults.Num() > 0) {
		UE_LOG(LogTemp, Warning, TEXT("Find session succes"));
		IOnlineSubsystem* OnlineSubsystem = IOnlineSubsystem::Get(); // získá subsystem

		if (OnlineSubsystem) //Kontroluje zda se získal subsystem
		{
			IOnlineSessionPtr SessionPtrRef = OnlineSubsystem->GetSessionInterface(); //Získá rozhraní subsystému
			if (SessionPtrRef) //Kontroluje zda se získal rozhraní
			{
				SessionPtrRef->OnJoinSessionCompleteDelegates.AddUObject(this, &UMultiplayerWidget::OnJoinSessionCompleted);
				SessionPtrRef->JoinSession(0, FName("MainSession"), sessionSearch->SearchResults[0]);
			}
		}
	}
}
void UMultiplayerWidget::OnJoinSessionCompleted(FName sessionName, EOnJoinSessionCompleteResult::Type result) {
	if (result == EOnJoinSessionCompleteResult::Success) {
		UE_LOG(LogTemp, Warning, TEXT("Join session succes"));
		FString JoinAddress;
		IOnlineSubsystem* OnlineSubsystem = IOnlineSubsystem::Get();
		if (OnlineSubsystem) {
			IOnlineSessionPtr SessionPtrRef = OnlineSubsystem->GetSessionInterface();
			if (SessionPtrRef) {
				if (SessionPtrRef->GetResolvedConnectString(FName("MainSession"), JoinAddress)) {
					UE_LOG(LogTemp, Warning, TEXT("Address: %s"), *JoinAddress);
					APlayerController* PlayerController = GetWorld()->GetFirstPlayerController();
					PlayerController->ClientTravel(JoinAddress, ETravelType::TRAVEL_Absolute);
				}
			}
		}
	}
}

void UMultiplayerWidget::DestroySession() {
	UE_LOG(LogTemp, Warning, TEXT("Starting destroiing session"));

	IOnlineSubsystem* OnlineSubsystem = IOnlineSubsystem::Get(); // získá subsystem

	if (OnlineSubsystem) //Kontroluje zda se získal subsystem
	{
		UE_LOG(LogTemp, Warning, TEXT("Destroiing session online subsystem"));
		IOnlineSessionPtr SessionPtrRef = OnlineSubsystem->GetSessionInterface(); //Získá rozhraní subsystému
		if (SessionPtrRef)	//Kontroluje zda se získal rozhraní
		{
			UE_LOG(LogTemp, Warning, TEXT("Destroiing session sessionPtrRef"));
			SessionPtrRef->OnDestroySessionCompleteDelegates.AddUObject(this, &UMultiplayerWidget::OnDestroyedSessionCompleted);
			SessionPtrRef->DestroySession(FName("MainSession"));
		}
	}
}
void UMultiplayerWidget::OnDestroyedSessionCompleted(FName sessionName, bool succesful) {
	FString sessionNamestring = sessionName.ToString();
	UE_LOG(LogTemp, Warning, TEXT("Was session: %s destroyed successfully?: %s"), *sessionNamestring, (succesful ? TEXT("true") : TEXT("false"))); //vypisuje do konzole zda se session zničila či ne
}

```

header file:

```auto
// Fill out your copyright notice in the Description page of Project Settings.

#pragma once

#include "CoreMinimal.h"
#include "Blueprint/UserWidget.h"

#include "Components/Button.h"
#include "Components/EditableTextBox.h"
#include "Components/CheckBox.h"

#include "OnlineSubsystem.h"
#include "OnlineSessionSettings.h"
#include "Interfaces/OnlineSessionInterface.h"
#include "OnlineSubsystemUtils.h"

#include "Kismet/GameplayStatics.h"

#include "Engine/Player.h"

#include "Blueprint/WidgetLayoutLibrary.h"

#include "MultiplayerWidget.generated.h"

/**
 * 
 */
UCLASS()
class NOXVIRIDUS_API UMultiplayerWidget : public UUserWidget
{
	GENERATED_BODY()

		virtual bool Initialize();
		
		
		//Deklarace UI prvků
		UPROPERTY(meta = (BindWidget))
		class UButton* HostGameBtn;

		UPROPERTY(meta = (BindWidget))
		UButton* JoinGameBtn;		

		UPROPERTY(meta = (BindWidget))
		class UEditableTextBox* ServerIPTbx;

		

		//Deklarace funkcí
		UFUNCTION()
		void CreateSession();
		UFUNCTION()
		void OnCreatedSessionCompleted(FName sessionName, bool successful);

		UFUNCTION()
		void FindJoinSession();
		UFUNCTION()
		void OnFindSessionCompleted(bool successful);

		void OnJoinSessionCompleted(FName sessionName, EOnJoinSessionCompleteResult::Type result);
		UFUNCTION()
		void OnDestroyedSessionCompleted(FName sessionName, bool successful);

		UFUNCTION()
		void GetMaxPlayers(const FText& ftext);
		UFUNCTION()
		void QuitGame();

	private:
		int maxPlayers;
		TSharedPtr<FOnlineSessionSearch> sessionSearch;
	public:
		UFUNCTION(BlueprintCallable, Category = "DestroySession")
		void DestroySession();
};

```

blueprint:

 ![image](https://d3kjluh73b9h9o.cloudfront.net/original/4X/6/4/9/649bb3b29adc2dd12008258b94f82c16f57cdf33.png)

---

<div class="post-metadata">

**Author:** ![brs-sebascova](https://d1ap1mz92jnks1.cloudfront.net/user_avatar/forums.unrealengine.com/brs-sebascova/32/1052483_2.png) [@brs-sebascova](https://forums.unrealengine.com/u/brs-sebascova)\
**Post date:** [January 27, 2025, 4:12pm UTC](https://forums.unrealengine.com/t/how-to-correctly-create-session-with-c/2304807/2 "2025-01-27T16:12:28Z")

</div>

Hello there @KKJMJ9! Let’s see what we can do here.

Investigating around the community, similar issues to yours have been encountered in other threads, with different approaches for resolution. Please check the methods applied here, to see if they help your scenario:

> [@Join Session does not work (Steam, Advanced sessions plugin)](https://forums.unrealengine.com/t/join-session-does-not-work-steam-advanced-sessions-plugin/1873895):
>
> Hey all, it has come to this, asking for help haha. I have followed some tutorials to get started, and from there I have read all the docs I can find, but I just cannot get join session to work when using Advanced Session Plugin with the OnlineSubsystemSteam. Let me lay out what I have done so far. Advanced Session Plugin, downloaded from here, for unreal 5.3.2 (the version I am using) [https://vreue4.com/advanced-sessions-binaries](https://vreue4.com/advanced-sessions-binaries) Advanced sessions and Advanced Steam Session plugins are ena…

> [@Help Needed: Online Session Joins are Timing Out](https://forums.unrealengine.com/t/help-needed-online-session-joins-are-timing-out/1205733):
>
> I’ve setup my project, currently to use the Online Session subsystem NULL; just testing local online sessions until the project is further in development. This was working on UE 5.1 and since I’ve moved up to 5.2 now when attempting to join the session it times out. I’ve tried launching game instances outside of the editor (so not in PIE) and packaging a build to put on a second PC and whenever I attempt to join the joining session stalls out for a bit then resets. In the logs I’m seeing that t…

---

<div class="post-metadata">

**Author:** ![KKJMJ9](https://d3kjluh73b9h9o.cloudfront.net/original/4X/2/8/5/28502927f1d97ba1051b3b47ccfe17233bf41ef0.png) [@KKJMJ9](https://forums.unrealengine.com/u/KKJMJ9)\
**Post date:** [January 28, 2025, 3:18pm UTC](https://forums.unrealengine.com/t/how-to-correctly-create-session-with-c/2304807/3 "2025-01-28T15:18:56Z")

</div>

[  
@brs-sebascova  
 ](https://dev.epicgames.com/community/api/user_profiles/tab-redirect/about?discourse_username=brs-sebascova)i think it’s having some problem with opening level for multiplayer: UGameplayStatics::OpenLevel(GetWorld(), FName(“MainMap”), true, TEXT(“?listen”));

becouse when i delete ?listen from options in blueprints OpenLevel(bt name) i also get no response

or is it besouse I use OnlineSubsystem???
