Realtime API

Overview

PhotonMatchmaking::RealtimeClient is the Photon Realtime networking layer.
It handles connection, matchmaking, room management, messaging and player state.

Header: RealtimeClient.h

Non-copyable, non-movable.

ClientConstructOptions

C++

struct ClientConstructOptions {
    PhotonCommon::StringType appId;
    PhotonCommon::StringType appVersion;
    ConnectionProtocol protocol = ConnectionProtocol::Default;
    bool useAlternativePorts = false;
    RegionSelectionMode regionSelectionMode = RegionSelectionMode::Default;
    bool autoLobbyStats = false;
    SerializationProtocol serialization = SerializationProtocol::Protocol1_8;
    std::optional<int> disconnectTimeoutMs;
    std::optional<int> pingIntervalMs;
    std::optional<bool> enableCrc;
    std::optional<int> sentCountAllowance;
    std::optional<uint8_t> quickResendAttempts;
    std::optional<int> limitOfUnreliableCommands;
};
Field Type Description
appId StringType Photon App ID from the dashboard.
appVersion StringType Application version string for matchmaking isolation.
protocol ConnectionProtocol Transport protocol.
useAlternativePorts bool Use alternative server ports.
regionSelectionMode RegionSelectionMode Region selection strategy.
autoLobbyStats bool Auto-request lobby statistics.
serialization SerializationProtocol Wire format version.
disconnectTimeoutMs optional<int> Override disconnect timeout in milliseconds.
pingIntervalMs optional<int> Override ping interval in milliseconds.
enableCrc optional<bool> Enable CRC checks on packets.
sentCountAllowance optional<int> Resend allowance count.
quickResendAttempts optional<uint8_t> Quick resend attempt count.
limitOfUnreliableCommands optional<int> Cap on the unreliable command queue.

ConnectOptions

C++

struct ConnectOptions {
    AuthenticationValues auth;
    PhotonCommon::StringType username;
    ServerType serverType = ServerType::NameServer;
    PhotonCommon::StringType serverAddress;
    bool tryUseDatagramEncryption = false;
    bool useBackgroundSendReceiveThread = true;
};
Field Type Description
auth AuthenticationValues Authentication credentials.
username StringType Display name for the player.
serverType ServerType Initial server to connect to.
serverAddress StringType Custom server address (overrides default).
tryUseDatagramEncryption bool Attempt datagram encryption.
useBackgroundSendReceiveThread bool Run network I/O on a background thread.

AuthenticationValues

C++

struct AuthenticationValues {
    PhotonCommon::StringType userId;
    CustomAuthenticationType type = CustomAuthenticationType::None;
    PhotonCommon::StringType parameters;
    std::variant<std::monostate, std::vector<uint8_t>,
        PhotonCommon::StringType, PropertyMap> data;
};
Field Type Description
userId StringType Unique user identifier.
type CustomAuthenticationType Auth provider type.
parameters StringType Auth query parameters.
data variant Auth data payload (empty, binary, string or property map).

Construction

C++

explicit RealtimeClient(const ClientConstructOptions& options);
~RealtimeClient();

Service Loop

C++

void Service(bool dispatchIncomingCommands = true);
void ServiceBasic();
bool SendOutgoingCommands();
bool SendAcksOnly();
bool DispatchIncomingCommands();
Method Description
Service(dispatch) Full service tick: send and optionally dispatch incoming. Call once per frame.
ServiceBasic() Minimal service tick (acks and keep-alive only).
SendOutgoingCommands() Flush the outgoing command queue. Returns true if data was sent.
SendAcksOnly() Send only acknowledgment packets.
DispatchIncomingCommands() Process and dispatch all queued incoming commands.

Connection

C++

Task<Result<void>> Connect();
Task<Result<void>> Connect(const ConnectOptions& options);
Task<Result<void>> Disconnect();
Task<Result<void>> Reconnect();
Method Description
Connect() Connect to Photon using default options.
Connect(options) Connect with explicit authentication and server options.
Disconnect() Gracefully disconnect from the server.
Reconnect() Reconnect to the last server after a disconnect.

Connection State

C++

ConnectionState GetState() const noexcept;
bool IsConnected() const noexcept;
bool IsInRoom() const noexcept;
bool IsInLobby() const noexcept;
DisconnectCause GetDisconnectCause() const;
Method Description
GetState() Returns the current ConnectionState enum value.
IsConnected() Returns true if connected to any Photon server.
IsInRoom() Returns true if currently in a room.
IsInLobby() Returns true if currently in a lobby.
GetDisconnectCause() Returns the reason for the last disconnect.

Regions

C++

Task<Result<std::vector<RegionInfo>>> AvailableRegions();
Task<Result<void>> SelectRegion(PhotonCommon::StringViewType region);
PhotonCommon::StringType GetBestRegion() const;
Method Description
AvailableRegions() Fetch the list of available regions with ping results.
SelectRegion(region) Select a specific region by code (e.g. "us", "eu").
GetBestRegion() Returns the region code with the lowest ping.

RegionInfo

C++

struct RegionInfo {
    PhotonCommon::StringType code;
    PhotonCommon::StringType server;
    int pingMs = -1;
};

Lobbies

C++

Task<Result<void>> JoinLobby(PhotonCommon::StringViewType name = {},
    LobbyType type = LobbyType::Default);
Task<Result<void>> LeaveLobby();
Task<Result<std::vector<LobbyStats>>> GetLobbyStats();
Method Description
JoinLobby(name, type) Join a named lobby. Empty name joins the default lobby.
LeaveLobby() Leave the current lobby.
GetLobbyStats() Fetch statistics for all lobbies.

LobbyStats

C++

struct LobbyStats {
    PhotonCommon::StringType name;
    LobbyType type = LobbyType::Default;
    int peerCount = 0;
    int roomCount = 0;
};

Rooms

All room operations return Task<Result<MutableRoomView>> (or Task<Result<void>> for leave).

C++

Task<Result<MutableRoomView>> CreateRoom(PhotonCommon::StringViewType name = {},
    const CreateRoomOptions& createOptions = {});

Task<Result<MutableRoomView>> JoinRoom(PhotonCommon::StringViewType name,
    const JoinRoomOptions& joinOptions = {});

Task<Result<MutableRoomView>> JoinOrCreateRoom(PhotonCommon::StringViewType name,
    const CreateRoomOptions& createOptions = {},
    const JoinRoomOptions& joinOptions = {});

Task<Result<MutableRoomView>> JoinRandomRoom(
    const MatchmakingOptions& matchmakingOptions = {});

Task<Result<MutableRoomView>> JoinRandomOrCreateRoom(
    const CreateRoomOptions& createOptions = {},
    const MatchmakingOptions& matchmakingOptions = {});

Task<Result<void>> LeaveRoom(bool willComeBack = false, bool sendAuthCookie = false);

std::optional<MutableRoomView> GetCurrentRoom() const;
Method Description
CreateRoom(name, options) Create a new room. Empty name generates a unique ID.
JoinRoom(name, options) Join an existing room by name.
JoinOrCreateRoom(name, ...) Join a room or create it if it does not exist.
JoinRandomRoom(options) Join a random room matching the filter criteria.
JoinRandomOrCreateRoom(...) Join a random room or create one if no match is found.
LeaveRoom(willComeBack, sendAuthCookie) Leave the current room. Set willComeBack for rejoin support.
GetCurrentRoom() Returns the current room view, or nullopt if not in a room.

Room List

C++

Task<Result<std::vector<RoomListing>>> GetRoomList(
    PhotonCommon::StringViewType lobby, PhotonCommon::StringViewType sqlFilter);
const std::vector<RoomListing>& GetCachedRoomList() const;

RoomListing

C++

struct RoomListing {
    PhotonCommon::StringType name;
    int playerCount = 0;
    uint8_t maxPlayers = 0;
    bool isOpen = false;
    DirectMode directMode = DirectMode::None;
    PropertyMap customProperties;
};

CreateRoomOptions

C++

struct CreateRoomOptions {
    bool isVisible = true;
    bool isOpen = true;
    uint8_t maxPlayers = 0;
    PropertyMap customProperties;
    std::vector<PhotonCommon::StringType> lobbyProperties;
    PhotonCommon::StringType lobbyName;
    LobbyType lobbyType = LobbyType::Default;
    int playerTtlMs = 0;
    int emptyRoomTtlMs = 0;
    bool suppressRoomEvents = false;
    bool publishUserId = false;
    DirectMode directMode = DirectMode::None;
    std::vector<PhotonCommon::StringType> plugins;
    std::vector<PhotonCommon::StringType> expectedUsers;
};
Field Type Description
isVisible bool Listed in lobby room lists.
isOpen bool Room is joinable.
maxPlayers uint8_t Max capacity (0 = unlimited).
customProperties PropertyMap Custom room properties.
lobbyProperties vector<StringType> Keys visible in lobby listings.
lobbyName StringType Target lobby name.
lobbyType LobbyType Target lobby type.
playerTtlMs int Player reconnect window in milliseconds.
emptyRoomTtlMs int Empty room lifetime in milliseconds.
suppressRoomEvents bool Suppress join/leave events.
publishUserId bool Share user IDs with other players.
directMode DirectMode Direct connection mode.
plugins vector<StringType> Server plugins to load.
expectedUsers vector<StringType> Slot reservation user IDs.

JoinRoomOptions

C++

struct JoinRoomOptions {
    bool rejoin = false;
    int cacheSliceIndex = 0;
    std::vector<PhotonCommon::StringType> expectedUsers;
};
Field Type Description
rejoin bool Rejoin a room left with willComeBack.
cacheSliceIndex int Event cache slice to start from.
expectedUsers vector<StringType> Slot reservation user IDs.

MatchmakingOptions

C++

struct MatchmakingOptions {
    PropertyMap filter;
    uint8_t maxPlayers = 0;
    MatchmakingMode mode = MatchmakingMode::FillRoom;
    PhotonCommon::StringType lobbyName;
    LobbyType lobbyType = LobbyType::Default;
    PhotonCommon::StringType sqlFilter;
    std::vector<PhotonCommon::StringType> expectedUsers;
};

MutableRoomView

Read-write view of the current room.
Returned by room join/create operations.

Read Access

Method Return Type Description
GetName() const StringType& Room name.
GetPlayerCount() int Current player count.
GetMaxPlayers() uint8_t Maximum player capacity.
IsOpen() bool Room is joinable.
IsVisible() bool Room is listed in lobby.
GetCustomProperties() const PropertyMap& Custom room properties.
GetPlayers() const vector<PlayerView>& All players in the room.
GetMasterClientId() int Actor number of the master client.
IsMasterClient() bool Is the local player the master client.
GetPlayerTtlMs() int Player reconnect window in milliseconds.
GetEmptyRoomTtlMs() int Empty room lifetime in milliseconds.
GetPublishUserId() bool Whether user IDs are shared.
GetDirectMode() DirectMode Direct connection mode.
GetExpectedUsers() const vector<StringType>& Reserved slot user IDs.
GetLobbyProperties() const vector<StringType>& Property keys visible in lobby.
GetSuppressRoomEvents() bool Whether join/leave events are suppressed.
GetPlugins() const vector<StringType>& Server plugins loaded.
GetLobbyName() const StringType& Lobby this room belongs to.
GetLobbyType() LobbyType Lobby type.

Mutations

Method Description
SetOpen(isOpen) Set whether the room is joinable.
SetVisible(isVisible) Set whether the room appears in lobby listings.
SetMaxPlayers(maxPlayers) Set the maximum player capacity.
SetProperties(props) Set custom room properties.
SetProperties(props, expected) Set properties with CAS (compare-and-swap) check.
RemoveProperties(keys) Remove custom properties by key.
SetLobbyProperties(props) Set which property keys are visible in lobby listings.
SetExpectedUsers(userIds) Reserve slots for specific users.
SetMasterClient(playerNumber) Transfer master client role to another player.
SetProperty(key, value) Set a single typed property (convenience template).

Players

C++

PlayerView GetLocalPlayer() const;
void SetPlayerName(PhotonCommon::StringViewType name, const WebFlags& webFlags = {});
bool SetPlayerProperties(const PropertyMap& properties, const WebFlags& webFlags = {});
template<typename T>
bool SetPlayerProperty(PhotonCommon::StringViewType key, const T& value);
bool RemovePlayerProperties(const std::vector<PhotonCommon::StringType>& keys,
    const WebFlags& webFlags = {});
PhotonCommon::StringType GetUserId() const;
Method Description
GetLocalPlayer() Returns the local player's PlayerView.
SetPlayerName(name) Set the local player's display name.
SetPlayerProperties(props) Set custom player properties.
SetPlayerProperty(key, value) Set a single typed player property (convenience template).
RemovePlayerProperties(keys) Remove player properties by key.
GetUserId() Returns the authenticated user ID.

PlayerView

C++

struct PlayerView {
    int number = 0;
    PhotonCommon::StringType name;
    PhotonCommon::StringType userId;
    PropertyMap customProperties;
    bool isInactive = false;
    bool isMasterClient = false;
};
Field Type Description
number int Actor number in the room.
name StringType Display name.
userId StringType Authenticated user ID.
customProperties PropertyMap Custom player properties.
isInactive bool True if the player left but may rejoin.
isMasterClient bool True if this player is the master client.

Events

SendEvent

C++

bool SendEvent(uint8_t eventCode, std::span<const uint8_t> data,
    const EventOptions& options = {});

template<typename T>
requires std::is_trivially_copyable_v<T>
bool SendEvent(uint8_t eventCode, const T& data, const EventOptions& options = {});

Send an event to players in the room.
The template overload serializes any trivially-copyable struct as raw bytes.

SendDirect

C++

int SendDirect(std::span<const uint8_t> data, const DirectMessageOptions& options = {});

template<typename T>
requires std::is_trivially_copyable_v<T>
int SendDirect(const T& data, const DirectMessageOptions& options = {});

Send a direct (peer-to-peer) message.
Returns the number of targets reached.

ChangeGroups

C++

bool ChangeGroups(const std::vector<uint8_t>& remove, const std::vector<uint8_t>& add);

Subscribe/unsubscribe from interest groups for event filtering.

EventOptions

C++

struct EventOptions {
    bool reliable = true;
    uint8_t channel = 0;
    ReceiverGroup receiverGroup = ReceiverGroup::Others;
    std::vector<int> targetPlayers;
    uint8_t interestGroup = 0;
    EventCache caching = EventCache::DoNotCache;
    bool encrypt = false;
    int cacheSliceIndex = 0;
    WebFlags webFlags;
};

DirectMessageOptions

C++

struct DirectMessageOptions {
    std::vector<int> targetPlayers;
    ReceiverGroup receiverGroup = ReceiverGroup::Others;
    bool fallbackRelay = false;
};

Friends

C++

Task<Result<std::vector<FriendInfo>>> FindFriends(
    const std::vector<PhotonCommon::StringType>& userIds);
const std::vector<FriendInfo>& GetFriendList() const;
int GetFriendListAge() const;

FriendInfo

C++

struct FriendInfo {
    PhotonCommon::StringType userId;
    bool isOnline = false;
    PhotonCommon::StringType roomName;
    bool isInRoom = false;
};

WebRPC

C++

Task<Result<WebRpcResponse>> WebRpc(PhotonCommon::StringViewType uriPath);
Task<Result<WebRpcResponse>> WebRpc(PhotonCommon::StringViewType uriPath,
    const PropertyMap& parameters, bool sendAuthCookie = false);

WebRpcResponse

C++

struct WebRpcResponse {
    int resultCode = 0;
    PhotonCommon::StringType errorString;
    PhotonCommon::StringType uriPath;
    PropertyMap returnData;
};

Custom Operations

C++

bool SendCustomOperation(uint8_t operationCode, const PropertyMap& params,
    bool reliable = true, uint8_t channel = 0, bool encrypt = false);
bool SendCustomAuthData(const AuthenticationValues& auth);
Method Description
SendCustomOperation(...) Send a custom operation to the server.
SendCustomAuthData(auth) Send additional authentication data after connect.

Stats and Configuration

C++

NetworkStats GetStats() const;
int GetServerTime() const;
void FetchServerTimestamp();
PhotonCommon::StringType GetMasterServerAddress() const;
void SetAutoJoinLobby(bool enabled);
Method Description
GetStats() Returns current network statistics.
GetServerTime() Returns the server timestamp in milliseconds.
FetchServerTimestamp() Request a fresh server timestamp.
GetMasterServerAddress() Returns the master server address.
SetAutoJoinLobby(enabled) Enable or disable automatic lobby join on connect.

Transport Tuning

Setter Getter Description
SetDisconnectTimeout(ms) GetDisconnectTimeout() Disconnect timeout in milliseconds.
SetPingInterval(ms) GetPingInterval() Ping interval in milliseconds.
SetSentCountAllowance(count) GetSentCountAllowance() Resend allowance count.
SetQuickResendAttempts(attempts) GetQuickResendAttempts() Quick resend attempt count.
SetCrcEnabled(enabled) GetCrcEnabled() CRC checks on packets.
SetLimitOfUnreliableCommands(limit) GetLimitOfUnreliableCommands() Cap on unreliable command queue.

Traffic Stats

C++

void SetTrafficStatsEnabled(bool enabled);
void ResetTrafficStats();
PhotonCommon::StringType GetVitalStatsToString(bool all = false) const;
TrafficStats GetTrafficStatsIncoming() const;
TrafficStats GetTrafficStatsOutgoing() const;
TrafficStatsGameLevel GetTrafficStatsGameLevel() const;
void ResetTrafficStatsMaximumCounters();

Broadcasters

All broadcasters use PhotonCommon::Broadcaster<Signature>.
Subscribe with .Subscribe(callback).

Broadcaster Signature Description
OnDisconnected void(DisconnectCause) Fired when disconnected from the server.
OnError void(ErrorCode, StringViewType) Fired on errors with an error code and message.
OnRoomPropertiesChanged void(const PropertyMap&) Fired when room properties are updated.
OnRoomListUpdated void(const vector<RoomListing>&) Fired when the lobby room list is updated.
OnMasterClientChanged void(int newId, int oldId) Fired when the master client changes.
OnPlayerJoined void(const PlayerView&) Fired when a player joins the room.
OnPlayerLeft void(int playerNumber, bool isInactive) Fired when a player leaves. isInactive is true if the player may rejoin.
OnPlayerPropertiesChanged void(int playerNumber, const PropertyMap&) Fired when a player's custom properties change.
OnEvent void(uint8_t eventCode, int senderId, span<const uint8_t> data) Fired when a custom event is received.
OnDirectMessage void(int senderId, span<const uint8_t> data, bool isRelay) Fired when a direct message is received.
OnLobbyStats void(const vector<LobbyStats>&) Fired when lobby statistics are updated.
OnCustomAuthStep void(const unordered_map<StringType, StringType>&) Fired during custom authentication with additional data from the auth provider.
OnAppStatsUpdated void() Fired when application-level statistics are updated.
OnWarning void(int warningCode) Fired on non-fatal warnings.
OnPropertiesChangeFailed void() Fired when a CAS property update fails.
OnCacheSliceChanged void(int cacheSliceIndex) Fired when the event cache slice changes.
OnDirectConnectionEstablished void(int remotePlayerId) Fired when a direct peer-to-peer connection is established.
OnDirectConnectionFailed void(int remotePlayerId) Fired when a direct peer-to-peer connection attempt fails.
OnCustomOperationResponse void(uint8_t opCode, int errorCode, StringViewType errorString, const PropertyMap& data) Fired when a custom operation response is received.
OnRoomJoined void() Fired when the local player successfully joins a room.
OnRoomLeft void() Fired when the local player leaves a room.

Enums

ConnectionState

Value Description
DisconnectedNot connected.
ConnectingConnection in progress.
ConnectedConnected to server (not in room).
JoiningRoomRoom join in progress.
InRoomIn a room.
LeavingRoomRoom leave in progress.
DisconnectingDisconnect in progress.

DisconnectCause

Value Code Description
None0No disconnect.
DisconnectByServerUserLimit1Server user limit reached.
ExceptionOnConnect2Exception during connect.
DisconnectByServer3Disconnected by server.
DisconnectByServerLogic4Disconnected by server logic.
TimeoutDisconnect5Connection timeout.
Exception6General exception.
InvalidAuthentication7Invalid authentication.
MaxCCUReached8Maximum CCU reached.
InvalidRegion9Invalid region.
OperationNotAllowedInCurrentState10Operation not allowed in current state.
CustomAuthenticationFailed11Custom authentication failed.
ClientVersionTooOld12Client version too old.
ClientVersionInvalid13Client version invalid.
DashboardVersionInvalid14Dashboard version invalid.
AuthenticationTicketExpired15Authentication ticket expired.
DisconnectByOperationLimit16Operation limit reached.

ErrorCode

Value Code Description
Ok0Success.
Unknown-1Unknown error.
ConnectionFailed1Connection failed.
Disconnected2Disconnected.
Timeout3Timeout.
ServerFull4Server full.
InvalidAuthentication10Invalid authentication.
CustomAuthenticationFailed11Custom auth failed.
AuthenticationTicketExpired12Auth ticket expired.
MaxCCUReached13Max CCU reached.
InvalidRegion14Invalid region.
ClientVersionTooOld15Client version too old.
RoomFull20Room is full.
RoomClosed21Room is closed.
RoomNotFound22Room not found.
RoomAlreadyExists23Room already exists.
NoMatchFound24No match found.
AlreadyJoined25Already joined.
SlotError26Slot reservation error.
OperationDenied30Operation denied.
OperationInvalid31Invalid operation.
OperationLimitReached32Operation limit reached.
RateLimited33Rate limited.
InternalServerError40Internal server error.
PluginError41Plugin error.
ServerDisconnect42Server disconnect.
NotConnected50Not connected.
NotInRoom51Not in a room.
InvalidState52Invalid state.

PropertyValue and PropertyMap

C++

using PropertyValue = std::variant<
    bool, int8_t, int16_t, int32_t, int64_t,
    float, double,
    PhotonCommon::StringType,
    std::vector<uint8_t>,
    std::vector<int32_t>,
    std::vector<float>,
    std::vector<PhotonCommon::StringType>
>;

using PropertyMap = std::unordered_map<PhotonCommon::StringType, PropertyValue>;

WebFlags

C++

struct WebFlags {
    bool httpForward = false;
    bool sendAuthCookie = false;
    bool sendSync = false;
    bool sendState = false;
};

Result and Task

Result<T>

Monadic result type wrapping either a success value or an Error.

Method Description
Ok(value)Create a success result.
Err(code, message)Create an error result.
IsOk()Returns true if successful.
IsErr()Returns true if an error.
GetValue()Returns the success value.
GetError()Returns the error.
GetErrorCode()Returns the error code.
ValueOr(default)Returns the value or a default.
Transform(f)Map the success value.
AndThen(f)Chain a fallible operation.
OrElse(f)Recover from an error.
TransformError(f)Map the error.

Result<void> is a specialization for operations with no return value.
Same API minus GetValue() and ValueOr().

Task<T>

C++20 coroutine-based async task.
Returned by all async RealtimeClient methods.
Move-only, non-copyable.

Method Description
IsReady()Returns true when the coroutine has completed.
Get()Block and retrieve the result.
await_ready()co_await support: ready check.
await_suspend(caller)co_await support: suspend.
await_resume()co_await support: resume and return result.

Supporting Enums

Enum Values
ReceiverGroup Others = 0, All = 1, MasterClient = 2
EventCache DoNotCache = 0, MergeCache = 1, ReplaceCache = 2, RemoveCache = 3, AddToRoomCache = 4, AddToRoomCacheGlobal = 5, RemoveFromRoomCache = 6, RemoveFromRoomCacheForActorsLeft = 7, SliceIncIndex = 10, SliceSetIndex = 11, SlicePurgeIndex = 12, SlicePurgeUpToIndex = 13
MatchmakingMode FillRoom = 0, SerialMatching = 1, RandomMatching = 2
LobbyType Default = 0, SqlLobby = 2, AsyncRandomLobby = 3
DirectMode None = 0, AllToOthers = 1, MasterToOthers = 2, AllToAll = 3, MasterToAll = 4
CustomAuthenticationType None = 255, Custom = 0, Steam = 1, Facebook = 2, Oculus = 3, PlayStation4 = 4, Xbox = 5, Viveport = 10, NintendoSwitch = 11, PlayStation5 = 12, Epic = 13, FacebookGaming = 15
Back to top