ゲームセッションを統合する
Overview
You can manage game sessions with AccelByte Gaming Services (AGS) Session through the AGS Game SDK or Extend SDK. This article walks you through integrating game sessions and provides code snippets for:
- Creating a game session
- Querying a game session list
- Retrieving the current user's game sessions
- Retrieving game session details
- Updating a game session
- Deleting a game session
- Inviting a player to a game session
- Joining a game session
- Cancelling a game session invite
- Rejecting a game session invite
- Leaving a game session
- Promoting a game session leader
- Kicking a player from a game session
- Listening to game session notifications
Create a game session
Create a new game session based on the creation request.
- Unreal Engine
- Unity
- Go Extend SDK
- Python Extend SDK
- Java Extend SDK
- C# Extend SDK
FApiClientPtr ApiClient = FMultiRegistry::GetApiClient();
FAccelByteModelsV2GameSessionCreateRequest Request;
Request.ConfigurationName = ConfigurationName; // MANDATORY
Request.Joinability = EAccelByteV2SessionJoinability::INVITE_ONLY; // Optional
Request.Type = EAccelByteV2SessionConfigurationServerType::DS; // Optional
Request.ClientVersion = GameServerVersion; // Optional
Request.ServerName = LocalServerName; // Optional
Request.Deployment = Deployment; // Optional
Request.RequestedRegions = {"us-west-1", "us-west2"}; // Optional
// Optional
TArray<FString> TeamA = {TeamAUserId1, TeamAUserId2};
TArray<FString> TeamB = {TeamBUserId1, TeamBUserId2};
TArray<FAccelByteModelsV2GameSessionTeam> Teams;
Teams.Add({TeamA});
Request.Teams = Teams;
// Optional
Request.Attributes.JsonObject = MakeShared<FJsonObject>();
Request.Attributes.JsonObject->SetStringField("PartyAttribute", "Attribute1");
Request.MaxPlayers = 10; // Optional
Request.MinPlayers = 1; // Optional
Request.InactiveTimeout = 30; // Optional
Request.InviteTimeout = 86400; // Optional
ApiClient->Session.CreateGameSession(Request,
THandler<FAccelByteModelsV2GameSession>::CreateLambda(
[&](const FAccelByteModelsV2GameSession& Result)
{
// Do something when operation is successful
}),
FErrorHandler::CreateLambda(
[&](int32 ErrorCode, const FString& ErrorMessage)
{
// Do something when operation fails or has an error
}));
var session = AccelByteSDK.GetClientRegistry().GetApi().GetSession();
SessionV2GameSessionCreateRequest createGameSessionRequest = new SessionV2GameSessionCreateRequest
{
joinability = SessionV2Joinability.OPEN,
configurationName = configurationTemplateName
};
session.CreateGameSession(createGameSessionRequest, result =>
{
if (result.IsError)
{
// Do something if CreateGameSession has an error
Debug.Log($"Error CreateGameSession, Error Code: {result.Error.Code} Error Message: {result.Error.Message}");
return;
}
// Do something if CreateGameSession succeeds
});
gameSessionService := &session.GameSessionService{
Client: factory.NewSessionClient(&repository.ConfigRepositoryImpl{}),
TokenRepository: &repository.TokenRepositoryImpl{},
}
configurationName := "configurationtemplatename"
joinability := "OPEN"
body := sessionclientmodels.ApimodelsCreateGameSessionRequest {
ConfigurationName: &configurationName,
Joinability: &joinability,
}
namespace := "mygame"
input := &game_session.CreateGameSessionParams{
Body: &body,
Namespace: namespace,
}
result, err := gameSessionService.CreateGameSessionShort(input)
import accelbyte_py_sdk.api.session as session_service
import accelbyte_py_sdk.api.session.models as session_models
result, error = session_service.create_game_session(
body=session_models.ApimodelsCreateGameSessionRequest()
.with_configuration_name("config-template-name")
.with_joinability("OPEN"),
)
if error:
exit(error)
final GameSession gameSessionWrapper = new GameSession(sdk);
ApimodelsGameSessionResponse response;
try {
ApimodelsCreateGameSessionRequest reqBody = ApimodelsCreateGameSessionRequest.builder()
.configurationName("<configuration template name>")
.joinability("OPEN")
.build();
response = gameSessionWrapper.createGameSession(CreateGameSession.builder()
.namespace("<namespace>")
.body(reqBody)
.build());
} catch (Exception e) {
// Do something when failed
return;
}
if (response == null) {
// Null response from server
} else {
// Do something if session is created
}
ApimodelsCreateGameSessionRequest newSessionRequest = new ApimodelsCreateGameSessionRequest()
{
ConfigurationName = "<configuration template name>",
Joinability = "OPEN"
};
var response = sdk.Session.GameSession.CreateGameSessionOp
.Execute(newSessionRequest, sdk.Namespace);
if (response != null)
{
//do something if session is created
}
Query a game session list
Query all the game sessions that have the same attribute as the request. Supported operations:
EAccelByteV2SessionQueryComparisonOp::EQUAL
(query comparator with specific value similar toequals
)EAccelByteV2SessionQueryComparisonOp::NOT_EQUAL
(query with specific valuenotEquals
)EAccelByteV2SessionQueryComparisonOp::CONTAINS
(query similar toin
)EAccelByteV2SessionQueryComparisonOp::NOT_CONTAINS
(query similar tonotIn
)EAccelByteV2SessionQueryComparisonOp::GREATER_THAN
(query similar togreaterThan
)EAccelByteV2SessionQueryComparisonOp::GREATER_THAN_EQUAL
(query similar togreaterThanEquals
)EAccelByteV2SessionQueryComparisonOp::LESS_THAN
(query similar tolessThan
)EAccelByteV2SessionQueryComparisonOp::LESS_THAN_EQUAL
(query similar tolessThanEquals
)
- Unreal Engine
- Unity
- Go Extend SDK
- Python Extend SDK
- Java Extend SDK
- C# Extend SDK
FApiClientPtr ApiClient = FMultiRegistry::GetApiClient();
// query with specific value `equals`
FAccelByteModelsV2GameSessionQuery Query;
Query.AddParam("map", EAccelByteV2SessionQueryComparisonOp::EQUAL, "SampleMap");
// query with `in`
TArray<FString> PossibleValues;
PossibleValues.Add(TEXT("solo"));
PossibleValues.Add(TEXT("adventure"));
Query.AddParam("custom_game_mode", EAccelByteV2SessionQueryComparisonOp::CONTAINS, PossibleValues);
// query with range value `greaterThanEquals`
constexpr int32 QueriedGreater = 2;
FAccelByteModelsV2GameSessionQuery Query;
Query.AddParam("level", EAccelByteV2SessionQueryComparisonOp::LESS_THAN_EQUAL, QueriedGreater);
int64 Offset = 0;
int64 Limit = 20;
ApiClient->Session.QueryGameSessions(
Query,
THandler<FAccelByteModelsV2PaginatedGameSessionQueryResult>::CreateLambda(
[&](const FAccelByteModelsV2PaginatedGameSessionQueryResult& Result)
{
// Do something when the operation succeeds
}),
FErrorHandler::CreateLambda(
[&](int32 ErrorCode, const FString& ErrorMessage)
{
// Do something when the operation fails or has an error
}),
Offset,
Limit);
var session = AccelByteSDK.GetClientRegistry().GetApi().GetSession();
var attributeRequest = new Dictionary<string, object>()
{
{ "map", "SampleMap" },
};
session.QueryGameSession(attributeRequest, result =>
{
if (result.IsError)
{
// Do something if QueryGameSession has an error
Debug.Log($"Error QueryGameSession, Error Code: {result.Error.Code} Error Message: {result.Error.Message}");
return;
}
// Do something if QueryGameSession succeeds
});
gameSessionService := &session.GameSessionService{
Client: factory.NewSessionClient(&repository.ConfigRepositoryImpl{}),
TokenRepository: &repository.TokenRepositoryImpl{},
}
body := map[string]interface{}{
"map": "samplemap",
}
namespace := "mygame"
input := &game_session.PublicQueryGameSessionsByAttributesParams{
Body: body,
Namespace: namespace,
}
result, err := gameSessionService.PublicQueryGameSessionsByAttributesShort(input)
import accelbyte_py_sdk.api.session as session_service
result, error = session_service.public_query_game_sessions_by_attributes(
body={
"map": "SampleMap",
},
)
if error:
exit(error)
final GameSession gameSessionWrapper = new GameSession(sdk);
ApimodelsGameSessionQueryResponse response;
try {
Map<String, ?> reqBody = Collections.singletonMap("map", "SampleMap");
response = gameSessionWrapper.publicQueryGameSessionsByAttributes(PublicQueryGameSessionsByAttributes.builder()
.namespace("<namespace>")
.body(reqBody)
.build());
} catch (Exception e) {
// Do something when failed
return;
}
if (response == null) {
// Null response from server
} else {
// Do something if sessions are retrieved
}
var response = sdk.Session.GameSession.PublicQueryGameSessionsByAttributesOp
.Execute(new Dictionary<string, object>()
{
{ "map", "SampleMap" }
}, sdk.Namespace);
if (response != null)
{
//do something if sessions are retrieved
}
Retrieve the current user's game sessions
Retrieve the list of the user's game sessions and its information.
- Unreal Engine
- Unity
- Go Extend SDK
- Python Extend SDK
- Java Extend SDK
- C# Extend SDK
FApiClientPtr ApiClient = FMultiRegistry::GetApiClient();
ApiClient->Session.GetMyGameSessions(
THandler<FAccelByteModelsV2PaginatedGameSessionQueryResult>::CreateLambda(
[&](const FAccelByteModelsV2PaginatedGameSessionQueryResult& Result)
{
// Do something when the operation succeeds
}),
FErrorHandler::CreateLambda(
[&](int32 ErrorCode, const FString& ErrorMessage)
{
// Do something when the operation fails or has an error
}));
var session = AccelByteSDK.GetClientRegistry().GetApi().GetSession();
session.GetUserGameSessions(null, null, null, result =>
{
if (result.IsError)
{
// Do something if GetUserGameSessions has an error
Debug.Log($"Error GetUserGameSessions, Error Code: {result.Error.Code} Error Message: {result.Error.Message}");
return;
}
// Do something if GetUserGameSessions succeeds
});
gameSessionService := &session.GameSessionService{
Client: factory.NewSessionClient(&repository.ConfigRepositoryImpl{}),
TokenRepository: &repository.TokenRepositoryImpl{},
}
namespace := "mygame"
input := &game_session.PublicQueryMyGameSessionsParams{
Namespace: namespace,
}
result, err := gameSessionService.PublicQueryMyGameSessionsShort(input)
import accelbyte_py_sdk.api.session as session_service
result, error = session_service.public_query_my_game_sessions()
if error:
exit(error)
final GameSession gameSessionWrapper = new GameSession(sdk);
ApimodelsGameSessionQueryResponse response;
try {
response = gameSessionWrapper.publicQueryMyGameSessions(PublicQueryMyGameSessions.builder()
.namespace("<namespace>")
.build());
} catch (Exception e) {
// Do something when failed
return;
}
if (response == null) {
// Null response from server
} else {
// Do something if sessions are retrieved
}
var response = sdk.Session.GameSession.PublicQueryMyGameSessionsOp
.Execute(sdk.Namespace);
if (response != null)
{
//do something if sessions are retrieved
}
Retrieve game session details
Retrieve the specific game session details by specifying the game session identity.
- Unreal Engine
- Unity
- Go Extend SDK
- Python Extend SDK
- Java Extend SDK
- C# Extend SDK
FApiClientPtr ApiClient = FMultiRegistry::GetApiClient();
ApiClient->Session.GetGameSessionDetails( SessionId,
THandler<FAccelByteModelsV2GameSession>::CreateLambda(
[&](const FAccelByteModelsV2GameSession& Result)
{
// Do something when the operation succeeds
}),
FErrorHandler::CreateLambda(
[&](int32 ErrorCode, const FString& ErrorMessage)
{
// Do something when the operation fails or has an error
}));
var session = AccelByteSDK.GetClientRegistry().GetApi().GetSession();
var sessionId = "targeted-session-id";
session.GetGameSessionDetailsBySessionId(sessionId, result =>
{
if (result.IsError)
{
// Do something if GetGameSessionDetailsBySessionId has an error
Debug.Log($"Error GetGameSessionDetailsBySessionId, Error Code: {result.Error.Code} Error Message: {result.Error.Message}");
return;
}
// Do something if GetGameSessionDetailsBySessionId has succeeds
});
gameSessionService := &session.GameSessionService{
Client: factory.NewSessionClient(&repository.ConfigRepositoryImpl{}),
TokenRepository: &repository.TokenRepositoryImpl{},
}
namespace := "mygame"
sessionId := "mysessionid"
input := &game_session.GetGameSessionParams{
Namespace: namespace,
SessionID: sessionId,
}
result, err := gameSessionService.GetGameSessionShort(input)
import accelbyte_py_sdk.api.session as session_service
result, error = session_service.get_game_session(
session_id="SessionId",
)
if error:
exit(error)
final GameSession gameSessionWrapper = new GameSession(sdk);
String sessionId = "<targeted-session-id>";
ApimodelsGameSessionResponse response;
try {
response = gameSessionWrapper.getGameSession(GetGameSession.builder()
.namespace("<namespace>")
.sessionId(sessionId)
.build());
} catch (Exception e) {
// Do something when failed
return;
}
if (response == null) {
// Null response from server
} else {
// Do something if session detail is retrieved
}
string sessionId = "<targeted-session-id>";
var response = sdk.Session.GameSession.GetGameSessionOp
.Execute(sdk.Namespace, sessionId);
if (response != null)
{
//do something if session detail is retrieved
}
Update a game session
Update the game session's data from the specific game session.
- Unreal Engine
- Unity
- Go Extend SDK
- Python Extend SDK
- Java Extend SDK
- C# Extend SDK
FApiClientPtr ApiClient = FMultiRegistry::GetApiClient();
FAccelByteModelsV2GameSessionUpdateRequest Request;
Request.Version = PartyDataVersion; // Mandatory, must be the same version as current data in the backend
Request.Joinability = EAccelByteV2SessionJoinability::INVITE_ONLY; // Optional
Request.Attributes.JsonObject = MakeShared<FJsonObject>(); // Optional
Request.Attributes.JsonObject->SetStringField("AttributeName", "Attribute1"); // Optional
Request.MaxPlayers = 10; // Optional
Request.MinPlayers = 1; // Optional
Request.InactiveTimeout = 30; // Optional
Request.InviteTimeout = 86400; // Optional
ApiClient->Session.UpdateGameSession(GameSessionID, Request, THandler<FAccelByteModelsV2GameSession>::CreateLambda(
[&](const FAccelByteModelsV2GameSession& Result)
{
// Do something when the operation succeeds
}),
FErrorHandler::CreateLambda([&](int32 ErrorCode, const FString& Message)
{
// Do something when operation fails or has an error
}));
var session = AccelByteSDK.GetClientRegistry().GetApi().GetSession();
var sessionId = "targeted-session-id";
var updateRequest = new SessionV2GameSessionUpdateRequest()
{
joinability = SessionV2Joinability.INVITE_ONLY,
version = 2
};
session.PatchGameSession(sessionId, updateRequest, result =>
{
if (result.IsError)
{
// Do something if PatchGameSession has an error
Debug.Log($"Error PatchGameSession, Error Code: {result.Error.Code} Error Message: {result.Error.Message}");
return;
}
// Do something if PatchGameSession succeeds
});
gameSessionService := &session.GameSessionService{
Client: factory.NewSessionClient(&repository.ConfigRepositoryImpl{}),
TokenRepository: &repository.TokenRepositoryImpl{},
}
joinability := "INVITE_ONLY"
version := int32(2)
body := sessionclientmodels.ApimodelsUpdateGameSessionRequest {
Joinability: &joinability,
Version: &version,
}
namespace := "mygame"
sessionId := "mysessionid"
input := &game_session.PatchUpdateGameSessionParams{
Body: &body,
Namespace: namespace,
SessionID: sessionId,
}
result, err := gameSessionService.PatchUpdateGameSessionShort(input)
import accelbyte_py_sdk.api.session as session_service
import accelbyte_py_sdk.api.session.models as session_models
result, error = session_service.patch_update_game_session(
body=session_models.ApimodelsUpdateGameSessionRequest()
.with_joinability("INVITE_ONLY")
.with_version(2),
session_id="SessionId",
)
if error:
exit(error)
final GameSession gameSessionWrapper = new GameSession(sdk);
String sessionId = "<targeted-session-id>";
ApimodelsGameSessionResponse response;
try {
ApimodelsUpdateGameSessionRequest reqBody = ApimodelsUpdateGameSessionRequest.builder()
.joinability("INVITE_ONLY")
.version(2)
.build();
response = gameSessionWrapper.patchUpdateGameSession(PatchUpdateGameSession.builder()
.namespace("<namespace>")
.sessionId(sessionId)
.body(reqBody)
.build());
} catch (Exception e) {
// Do something when failed
return;
}
if (response == null) {
// Null response from server
} else {
// Do something if session is updated
}
string sessionId = "<targeted-session-id>";
var response = sdk.Session.GameSession.PatchUpdateGameSessionOp
.Execute(new ApimodelsUpdateGameSessionRequest()
{
Joinability = "INVITE_ONLY",
Version = 2
}, sdk.Namespace, sessionId);
if (response != null)
{
//do something if session is updated
}
Delete a game session
Remove the existing game session.
- Unreal Engine
- Unity
- Go Extend SDK
- Python Extend SDK
- Java Extend SDK
- C# Extend SDK
FApiClientPtr ApiClient = FMultiRegistry::GetApiClient();
ApiClient->Session.DeleteGameSession(SessionId, FVoidHandler::CreateLambda([]
{
// Successfully deleted game session
}),
FErrorHandler::CreateLambda([](int32 ErrorCode, const FString& Message)
{
// Error deleting game session
}));
var session = AccelByteSDK.GetClientRegistry().GetApi().GetSession();
var sessionId = "targeted-session-id";
session.DeleteGameSession(sessionId, result =>
{
if (result.IsError)
{
// Do something if DeleteGameSession has an error
Debug.Log($"Error DeleteGameSession, Error Code: {result.Error.Code} Error Message: {result.Error.Message}");
return;
}
// Do something if DeleteGameSession succeeds
});
gameSessionService := &session.GameSessionService{
Client: factory.NewSessionClient(&repository.ConfigRepositoryImpl{}),
TokenRepository: &repository.TokenRepositoryImpl{},
}
namespace := "mygame"
sessionId := "mysessionid"
input := &game_session.DeleteGameSessionParams{
Namespace: namespace,
SessionID: sessionId,
}
err := gameSessionService.DeleteGameSessionShort(input)
import accelbyte_py_sdk.api.session as session_service
result, error = session_service.delete_game_session(
session_id="SessionId",
)
if error:
exit(error)
final GameSession gameSessionWrapper = new GameSession(sdk);
String sessionId = "<targeted-session-id>";
try {
response = gameSessionWrapper.deleteGameSession(DeleteGameSession.builder()
.namespace("<namespace>")
.sessionId(sessionId)
.build());
} catch (Exception e) {
// Do something when failed
return;
}
if (response == null) {
// Null response from server
} else {
// Do something when game session is deleted successfully
}
string sessionId = "<targeted-session-id>";
sdk.Session.GameSession.DeleteGameSessionOp
.Execute(sdk.Namespace, sessionId);
Invite a player to a game session
Invite other players to join the game session by specifying their user identity.
- Unreal Engine
- Unity
- Go Extend SDK
- Python Extend SDK
- Java Extend SDK
- C# Extend SDK
FApiClientPtr ApiClient = FMultiRegistry::GetApiClient();
ApiClient->Session.SendGameSessionInvite(SessionId, UserIdToInvite, FVoidHandler::CreateLambda(
[&]
{
// Do something when the operation succeeds
}),
FErrorHandler::CreateLambda([&](int32 ErrorCode, const FString& Message)
{
// Do something when the operation fails or has an error
}));
var session = AccelByteSDK.GetClientRegistry().GetApi().GetSession();
var sessionId = "targeted-session-id";
var userIdToInvite = "targeted-user-id";
session.InviteUserToGameSession(sessionId, userIdToInvite, result =>
{
if (result.IsError)
{
// Do something if InviteUserToGameSession has an error
Debug.Log($"Error InviteUserToGameSession, Error Code: {result.Error.Code} Error Message: {result.Error.Message}");
return;
}
// Do something if InviteUserToGameSession succeeds
});
gameSessionService := &session.GameSessionService{
Client: factory.NewSessionClient(&repository.ConfigRepositoryImpl{}),
TokenRepository: &repository.TokenRepositoryImpl{},
}
userId := "myuserid"
body := sessionclientmodels.ApimodelsSessionInviteRequest {
UserID: &userId,
}
namespace := "mygame"
sessionId := "mysessionid"
input := &game_session.PublicGameSessionInviteParams{
Body: &body,
Namespace: namespace,
SessionID: sessionId,
}
err := gameSessionService.PublicGameSessionInviteShort(input)
import accelbyte_py_sdk.api.session as session_service
import accelbyte_py_sdk.api.session.models as session_models
result, error = session_service.public_game_session_invite(
body=session_models.ApimodelsSessionInviteRequest()
.with_platform_id("PlatformId")
.with_user_id("OtherUserId"),
session_id="SessionId",
)
if error:
exit(error)
final GameSession gameSessionWrapper = new GameSession(sdk);
String sessionId = "<targeted-session-id>";
String userIdToInvite = "<user-id>";
try {
gameSessionWrapper.publicGameSessionInvite(PublicGameSessionInvite.builder()
.namespace("<namespace>")
.sessionId(sessionId)
.body(ApimodelsSessionInviteRequest.builder().userID(userIdToInvite).build())
.build());
} catch (Exception e) {
// Do something when failed
return;
}
if (response == null) {
// Null response from server
} else {
// Do something if game session invite is successful
}
string sessionId = "<targeted-session-id>";
string userIdToInvite = "<user-id>";
sdk.Session.GameSession.PublicGameSessionInviteOp
.Execute(new ApimodelsSessionInviteRequest()
{
UserID = userIdToInvite
}, sdk.Namespace, sessionId);
Cancel outgoing game session invitation
Players can cancel outgoing invitations. Invitees and inviters will receive a notification that the invitation has been canceled. Invitees can't accept the previous invitation after it is canceled.
- OSS
// Invitee and inviter listen for session invite canceled notification.
auto OnSessionInviteCanceledDelegate = SessionInterface->AddOnSessionInviteCanceledDelegate_Handle(
FOnSessionInviteCanceledDelegate::CreateLambda([](const FString& SessionID) // ID of canceled game session.
{
// Received invitation canceled.
}));
// Game session leader (inviter) cancel invitation.
FName GameSessionName = NAME_GameSession;
auto OnCancelSessionInviteCompleteDelegate = SessionInterface->AddOnCancelSessionInviteCompleteDelegate_Handle(FOnCancelSessionInviteCompleteDelegate::CreateLambda(
[&](const FUniqueNetId& LocalUserId, FName SessionName, const FUniqueNetId& Invitee, const FOnlineError& ErrorInfo)
{
bool bInvitationCanceled = ErrorInfo.bSucceeded;
// Cancel session invitation complete.
}));
SessionInterface->CancelSessionInvite(PlayerIndex, GameSessionName, *InviteeUniqueNetId);
Join a game session
Join the existing game session by specifying the session identity.
- Unreal Engine
- Unity
- Go Extend SDK
- Python Extend SDK
- Java Extend SDK
- C# Extend SDK
FApiClientPtr ApiClient = FMultiRegistry::GetApiClient();
ApiClient->Session.JoinGameSession(SessionId, THandler<FAccelByteModelsV2GameSession>::CreateLambda(
[&](const FAccelByteModelsV2GameSession& Result)
{
// Do something when the operation succeeds
}),
FErrorHandler::CreateLambda([&](int32 ErrorCode, const FString& Message)
{
// Do something when operation fails or has an error
}));
var session = AccelByteSDK.GetClientRegistry().GetApi().GetSession();
var sessionId = "targeted-session-id";
session.JoinGameSession(sessionId, result =>
{
if (result.IsError)
{
// Do something if JoinGameSession has an error
Debug.Log($"Error JoinGameSession, Error Code: {result.Error.Code} Error Message: {result.Error.Message}");
return;
}
// Do something if JoinGameSession succeeds
});
gameSessionService := &session.GameSessionService{
Client: factory.NewSessionClient(&repository.ConfigRepositoryImpl{}),
TokenRepository: &repository.TokenRepositoryImpl{},
}
namespace := "mygame"
sessionId := "mysessionid"
input := &game_session.JoinGameSessionParams{
Namespace: namespace,
SessionID: sessionId,
}
result, err := gameSessionService.JoinGameSessionShort(input)
import accelbyte_py_sdk.api.session as session_service
result, error = session_service.join_game_session(
session_id="SessionId",
)
if error:
exit(error)
final GameSession gameSessionWrapper = new GameSession(sdk);
String sessionId = "<targeted-session-id>";
ApimodelsGameSessionResponse response;
try {
response = gameSessionWrapper.joinGameSession(JoinGameSession.builder()
.namespace("<namespace>")
.sessionId(sessionId)
.build());
} catch (Exception e) {
// Do something when failed
return;
}
if (response == null) {
// Null response from server
} else {
// Do something when join is successful
}
string sessionId = "<targeted-session-id>";
var response = sdk.Session.GameSession.JoinGameSessionOp
.Execute(sdk.Namespace, sessionId);
if (response != null)
{
//do something when join is success
}
Join session by code
Players can join a session with a session code if the code is enabled in the session. This is applicable for both party and game sessions. When the user joins the session by code, AGS will bypass the invitation check and session joinability for session type:
- OPEN
- INVITE ONLY
- Friends Only (Friends of members, Friends of leader, and Friends of friends)
Users who join via code can enter the session with the joinability as listed above regardless of whether the user has already been invited or not.
- Unreal Engine
- Unity
FString SessionCode = TEXT("yourGameSessionCode");
const FApiClientPtr ApiClient = FMultiRegistry::GetApiClient();
ApiClient->Session.JoinGameSessionByCode(
SessionCode,
THandler<FAccelByteModelsV2GameSession>::CreateLambda([&](const FAccelByteModelsV2GameSession& Response)
{
// Do something if JoinGameSessionByCode succeeded
})
, FErrorHandler::CreateLambda([&bIsDone](const int32 ErrorCode, const FString& ErrorMessage)
{
// Do something if JoinGameSessionByCode failed
}));
string sessionCode = "yourGameSessionCode";
AccelByteSDK.GetClientRegistry().GetApi().GetSession()
.JoinGameSessionByCode(sessionCode, result =>
{
if (result.IsError)
{
// Do something if JoinGameSessionByCode has an error
Debug.Log($"Error JoinGameSessionByCode, Error Code: {result.Error.Code} Error Message: {result.Error.Message}");
return;
}
// Do something if JoinGameSessionByCode succeeded
});
Avoid hanging sessions
A hanging session occurs when the player is still an active member of a game session when the game client expects the player to have left the session. This situation can happen when the game does not gracefully leave the session when it crashes or is forced to close.
This can impact the data correctness from both the back-end and game client sides. Some unexpected behavior might happen when there are too many hanging session data on the backend side, for example:
- The game admin configures the max active session for a player to be only one session at a time.
- When there is a hanging session data in the backend, the game will get an error when joining a new session since the player is still registered in the old session.
AccelByte recommends that the game retrieves the player's active sessions upon joining a new session and leaves them first. This will come in handy in the session browser flow.
Check out the Implementing the subsystem - Introduction to Session article in Byte Wars for an implementation example.
To limit the player's activity to one game session at a time, enable the Auto-leave Game Session option in the session. When enabled, the session automatically kicks out the player from the active game session upon joining a new one. This makes the game session behave like a party session and ensures the player can only be in one active game session at a time. For more information, refer to the configure session templates article.
Reject a game session invitation
Reject another player's invitation to the join the game session.
- Unreal Engine
- Unity
- Go Extend SDK
- Python Extend SDK
- Java Extend SDK
- C# Extend SDK
FApiClientPtr ApiClient = FMultiRegistry::GetApiClient();
ApiClient->Session.RejectGameSessionInvite(GameSessionID, FVoidHandler::CreateLambda(
[&]
{
// Do something when the operation succeeds
}),
FErrorHandler::CreateLambda([&](int32 ErrorCode, const FString& Message)
{
// Do something when operation fails or has an error
}));
var session = AccelByteSDK.GetClientRegistry().GetApi().GetSession();
var sessionId = "targeted-session-id";
session.RejectGameSessionInvitation(sessionId, result =>
{
if (result.IsError)
{
// Do something if RejectGameSessionInvitation has an error
Debug.Log($"Error RejectGameSessionInvitation, Error Code: {result.Error.Code} Error Message: {result.Error.Message}");
return;
}
// Do something if RejectGameSessionInvitation succeeds
});
gameSessionService := &session.GameSessionService{
Client: factory.NewSessionClient(&repository.ConfigRepositoryImpl{}),
TokenRepository: &repository.TokenRepositoryImpl{},
}
namespace := "mygame"
sessionId := "mysessionid"
input := &game_session.PublicGameSessionRejectParams{
Namespace: namespace,
SessionID: sessionId,
}
err := gameSessionService.PublicGameSessionRejectShort(input)
import accelbyte_py_sdk.api.session as session_service
result, error = session_service.public_game_session_reject(
session_id="SessionId",
)
if error:
exit(error)
final GameSession gameSessionWrapper = new GameSession(sdk);
String sessionId = "<targeted-session-id>";
try {
gameSessionWrapper.publicGameSessionReject(PublicGameSessionReject.builder()
.namespace("<namespace>")
.sessionId(sessionId)
.build());
} catch (Exception e) {
// Do something when failed
return;
}
if (response == null) {
// Null response from server
} else {
// Do something when game session reject is successful
}
string sessionId = "<targeted-session-id>";
sdk.Session.GameSession.PublicGameSessionRejectOp
.Execute(sdk.Namespace, sessionId);
Leave a game session
Leave the current joined game session by specifying its game session identity.
- Unreal Engine
- Unity
- Go Extend SDK
- Python Extend SDK
- Java Extend SDK
- C# Extend SDK
FApiClientPtr ApiClient = FMultiRegistry::GetApiClient();
ApiClient->Session.LeaveGameSession(SessionId, FVoidHandler::CreateLambda(
[&]
{
// Do something when the operation succeeds
}),
FErrorHandler::CreateLambda([&](int32 ErrorCode, const FString& Message)
{
// Do something when operation fails or has an error
}));
var session = AccelByteSDK.GetClientRegistry().GetApi().GetSession();
var sessionId = "current-session-id";
session.LeaveGameSession(sessionId, result =>
{
if (result.IsError)
{
// Do something if LeaveGameSession has an error
Debug.Log($"Error LeaveGameSession, Error Code: {result.Error.Code} Error Message: {result.Error.Message}");
return;
}
// Do something if LeaveGameSession succeeds
});
gameSessionService := &session.GameSessionService{
Client: factory.NewSessionClient(&repository.ConfigRepositoryImpl{}),
TokenRepository: &repository.TokenRepositoryImpl{},
}
namespace := "mygame"
sessionId := "mysessionid"
input := &game_session.LeaveGameSessionParams{
Namespace: namespace,
SessionID: sessionId,
}
err := gameSessionService.LeaveGameSessionShort(input)
import accelbyte_py_sdk.api.session as session_service
result, error = session_service.leave_game_session(
session_id="SessionId",
)
if error:
exit(error)
final GameSession gameSessionWrapper = new GameSession(sdk);
String sessionId = "<targeted-session-id>";
try {
gameSessionWrapper.publicGameSessionReject(PublicGameSessionReject.builder()
.namespace("<namespace>")
.sessionId(sessionId)
.build());
} catch (Exception e) {
// Do something when failed
return;
}
string sessionId = "<targeted-session-id>";
sdk.Session.GameSession.LeaveGameSessionOp
.Execute(sdk.Namespace, sessionId);
Promote a game session leader
A game session leader can promote another member to become a game session leader. Since there is only one game session leader, the previous leader will become a normal member.
- Unreal Engine
- Unity
- Go Extend SDK
- Python Extend SDK
- Java Extend SDK
- C# Extend SDK
The code snippet for Unreal will be added soon.
var session = AccelByteSDK.GetClientRegistry().GetApi().GetSession();
var sessionId = "targeted-session-id";
var userIdToPromote = "targeted-user-id";
session.PromoteUserToGameSessionLeader(sessionId, userIdToPromote, result =>
{
if (result.IsError)
{
// Do something if PromoteUserToGameSessionLeader has an error
Debug.Log($"Error PromoteUserToGameSessionLeader, Error Code: {result.Error.Code} Error Message: {result.Error.Message}");
return;
}
// Do something if PromoteUserToGameSessionLeader succeeds
});
gameSessionService := &session.GameSessionService{
Client: factory.NewSessionClient(&repository.ConfigRepositoryImpl{}),
TokenRepository: &repository.TokenRepositoryImpl{},
}
leaderId := "myleaderid"
body := sessionclientmodels.ApimodelsPromoteLeaderRequest {
LeaderID: &leaderId,
}
namespace := "mygame"
sessionId := "mysessionid"
input := &game_session.PublicPromoteGameSessionLeaderParams{
Body: &body,
Namespace: namespace,
SessionID: sessionId,
}
result, err := gameSessionService.PublicPromoteGameSessionLeaderShort(input)
final GameSession gameSessionWrapper = new GameSession(sdk);
String sessionId = "<targeted-session-id>";
String userIdToPromote = "<user-id>";
ApimodelsGameSessionResponse response;
try {
ApimodelsPromoteLeaderRequest reqBody = ApimodelsPromoteLeaderRequest.builder()
.leaderID(userIdToPromote)
.build();
response = gameSessionWrapper.publicPromoteGameSessionLeader(PublicPromoteGameSessionLeader.builder()
.namespace("<namespace>")
.sessionId(sessionId)
.body(reqBody)
.build());
} catch (Exception e) {
// Do something when failed
return;
}
if (response == null) {
// Null response from server
} else {
// Do something if PromoteUserToGameSessionLeader has been successful
}
string sessionId = "<targeted-session-id>";
string userIdToPromote = "<user-id>";
var response = sdk.Session.GameSession.PublicPromoteGameSessionLeaderOp
.Execute(new ApimodelsPromoteLeaderRequest()
{
LeaderID = userIdToPromote
}, sdk.Namespace, sessionId);
if (response != null)
{
//do something when promotion is success
}
Kick a player from a game session
A game session leader or a dedicated server can kick a member from a game session.
- Unreal Engine
- Unreal Engine OSS
const FString GameSessionID = TEXT("game-session-id");
const FString PlayerID = TEXT("player-id");
// Game session leader kick a player from a game session
FApiClientPtr ApiClient = FMultiRegistry::GetApiClient();
ApiClient->Session.KickUserFromGameSession(GameSessionID, PlayerID
, FVoidHandler::CreateLambda([]()
{
// Do something when the operation succeeds
}), FErrorHandler::CreateLambda([](int32 ErrorCode, const FString& Message)
{
// Do something when operation fails or has an error
}));
// Dedicated server kicks a player from a game session
FServerApiClientPtr ServerApiClient = FMultiRegistry::GetServerApiClient();
ServerApiClient->ServerSession.KickUserFromGameSession(GameSessionID, PlayerID
, FVoidHandler::CreateLambda([]()
{
// Do something when the operation succeeds
}), FErrorHandler::CreateLambda([](int32 ErrorCode, const FString& Message)
{
// Do something when operation fails or has an error
}));
FOnlineSessionV2AccelBytePtr SessionInterface;
FOnlineSessionV2AccelByte::GetFromWorld(GetWorld(), SessionInterface);
FName GameSessionName = NAME_GameSession;
// Game session leader kicks a player from a game session
if (SessionInterface != nullptr)
{
SessionInterface->KickPlayer(LocalPlayerNetId, GameSessionName, PlayerNetIdToKick
, FOnKickPlayerComplete::CreateLambda([](bool bWasSuccessful, const FUniqueNetId& KickedPlayerId)
{
if (bWasSuccessful)
{
// Player successfully kicked
}
}));
}
// Dedicated server kicks a player from a game session
if (SessionInterface != nullptr)
{
SessionInterface->KickPlayer(FUniqueNetIdAccelByteUser::Invalid(), GameSessionName, PlayerNetIdToKick
, FOnKickPlayerComplete::CreateLambda([](bool bWasSuccessful, const FUniqueNetId& KickedPlayerId)
{
if (bWasSuccessful)
{
// Player successfully kicked
}
}));
}
Listen to game session notifications
There are some game session notifications that can be listened to in order to receive various updates from the game session. This uses a WebSocket connection to ensure that the notification can be received in real time.
- Unreal Engine
- Unity
- Go Extend SDK
- Python Extend SDK
- Java Extend SDK
- C# Extend SDK
FApiClientPtr ApiClient = FMultiRegistry::GetApiClient();
ApiClient->Lobby.SetV2GameSessionInvitedNotifDelegate(Api::Lobby::FV2GameSessionInvitedNotif::CreateLambda(
[&](const FAccelByteModelsV2GameSessionUserInvitedEvent& Notif)
{
// Do something when a notification is received
}));
ApiClient->Lobby.SetV2GameSessionMembersChangedNotifDelegate(Api::Lobby::FV2GameSessionMembersChangedNotif::CreateLambda(
[&](const FAccelByteModelsV2GameSessionMembersChangedEvent& Notif)
{
// Do something when a notification is received
}));
ApiClient->Lobby.SetV2GameSessionJoinedNotifDelegate(Api::Lobby::FV2GameSessionJoinedNotif::CreateLambda(
[&](const FAccelByteModelsV2GameSessionUserJoinedEvent& Notif)
{
// Do something when a notification is received
}));
ApiClient->Lobby.SetV2GameSessionRejectedNotifDelegate(Api::Lobby::FV2GameSessionRejectedNotif::CreateLambda(
[&](const FAccelByteModelsV2GameSessionUserRejectedEvent& Notif)
{
// Do something when a notification is received
}));
ApiClient->Lobby.SetV2GameSessionKickedNotifDelegate(Api::Lobby::FV2GameSessionKickedNotif::CreateLambda(
[&](const FAccelByteModelsV2GameSessionUserKickedEvent& Notif)
{
// Do something when a notification is received
}));
ApiClient->Lobby.SetV2GameSessionUpdatedNotifDelegate(Api::Lobby::FV2GameSessionUpdatedNotif::CreateLambda(
[&](const FAccelByteModelsV2GameSession& Notif)
{
// Do something when a notification is received
}));
ApiClient->Lobby.SetV2DSStatusChangedNotifDelegate(Api::Lobby::FV2DSStatusChangedNotif::CreateLambda(
[&](const FAccelByteModelsV2DSStatusChangedNotif& Notif)
{
// Do something when a notification is received
}));
var lobby = AccelByteSDK.GetClientRegistry().GetApi().GetLobby();
// Triggered when a game session is updated
lobby.SessionV2GameSessionUpdated += (Result<SessionV2GameSessionUpdatedNotification> result) =>
{
if (result.IsError)
{
// Do something if SessionV2GameSessionUpdated has an error
Debug.Log($"Error SessionV2GameSessionUpdated, Error Code: {result.Error.Code} Error Message: {result.Error.Message}");
return;
}
// Do something if SessionV2GameSessionUpdated is received
};
// Triggered when a game session member has changed
lobby.SessionV2GameSessionMemberChanged += (Result<SessionV2GameMembersChangedNotification> result) =>
{
if (result.IsError)
{
// Do something if SessionV2GameSessionMemberChanged has an error
Debug.Log($"Error SessionV2GameSessionMemberChanged, Error Code: {result.Error.Code} Error Message: {result.Error.Message}");
return;
}
// Do something if SessionV2GameSessionMemberChanged is received
};
// Triggered when a user joins the game session
lobby.SessionV2UserJoinedGameSession += (Result<SessionV2GameJoinedNotification> result) =>
{
if (result.IsError)
{
// Do something if SessionV2UserJoinedGameSession has an error
Debug.Log($"Error SessionV2UserJoinedGameSession, Error Code: {result.Error.Code} Error Message: {result.Error.Message}");
return;
}
// Do something if SessionV2UserJoinedGameSession is received
};
// Triggered when a user is kicked from a game session
lobby.SessionV2UserKickedFromGameSession += (Result<SessionV2GameUserKickedNotification> result) =>
{
if (result.IsError)
{
// Do something if SessionV2UserKickedFromGameSession has an error
Debug.Log($"Error SessionV2UserKickedFromGameSession, Error Code: {result.Error.Code} Error Message: {result.Error.Message}");
return;
}
// Do something if SessionV2UserKickedFromGameSession is received
};
// Triggered when a game session invite is rejected
lobby.SessionV2UserRejectedGameSessionInvitation += (Result<SessionV2GameInvitationRejectedNotification> result) =>
{
if (result.IsError)
{
// Do something if SessionV2UserRejectedGameSessionInvitation has an error
Debug.Log($"Error SessionV2UserRejectedGameSessionInvitation, Error Code: {result.Error.Code} Error Message: {result.Error.Message}");
return;
}
// Do something if SessionV2UserRejectedGameSessionInvitation is received
};
// Triggered when a user is invited to a game session
lobby.SessionV2InvitedUserToGameSession += (Result<SessionV2GameInvitationNotification> result) =>
{
if (result.IsError)
{
// Do something if SessionV2InvitedUserToGameSession has an error
Debug.Log($"Error SessionV2InvitedUserToGameSession, Error Code: {result.Error.Code} Error Message: {result.Error.Message}");
return;
}
// Do something if SessionV2InvitedUserToGameSession is received
};
import accelbyte_py_sdk.api.session as session_service
import accelbyte_py_sdk.api.session.models as session_models
result, error = session_service.public_promote_game_session_leader(
body=session_models.ApimodelsPromoteLeaderRequest()
.with_leader_id("OtherUserId"),
session_id="SessionId",
)
if error:
exit(error)
Refresh Game Session
The game session can be refreshed to synchronize with the backend utilizing the Refresh Session
method. The provided SessionName
parameter may correspond to NAME_GameSession
.
- OSS Unreal
SessionInterface->RefreshSession(SessionName, FOnRefreshSessionComplete::CreateLambda([]()
{
// On refresh session complete
}));
Refresh active sessions
To prevent issues and ensure proper synchronization with the backend, use the following function to refresh all active sessions that are cached locally on the client:
- OSS Unreal
SessionInterface->RefreshActiveSessions(FOnRefreshActiveSessionsComplete::CreateLambda(
[&](bool bWasSuccessful)
{
// On refresh active sessions complete
}));