Class: LoadBalancingClient

Photon.LoadBalancing.LoadBalancingClient(protocol, appId, appVersion)

Implements the Photon LoadBalancing workflow. This class should be extended to handle system or custom events and operation responses.

Constructor

new LoadBalancingClient(protocol, appId, appVersion)

Parameters:
Name Type Description
protocol Photon.ConnectionProtocol Connecton protocol.
appId string Cloud application ID.
appVersion string Cloud application version.

Members

(static, readonly) PeerErrorCode

Enum for client peers error codes.

Properties:
Name Type Description
Ok number No Error.
MasterError number General Master server peer error.
MasterConnectFailed number Master server connection error.
MasterConnectClosed number Disconnected from Master server.
MasterTimeout number Disconnected from Master server for timeout.
MasterEncryptionEstablishError number Master server encryption establishing failed.
MasterAuthenticationFailed number Master server authentication failed.
GameError number General Game server peer error.
GameConnectFailed number Game server connection error.
GameConnectClosed number Disconnected from Game server.
GameTimeout number Disconnected from Game server for timeout.
GameEncryptionEstablishError number Game server encryption establishing failed.
GameAuthenticationFailed number Game server authentication failed.
NameServerError number General NameServer peer error.
NameServerConnectFailed number NameServer connection error.
NameServerConnectClosed number Disconnected from NameServer.
NameServerTimeout number Disconnected from NameServer for timeout.
NameServerEncryptionEstablishError number NameServer encryption establishing failed.
NameServerAuthenticationFailed number NameServer authentication failed.

(static, readonly) State

Enum for client states.

Properties:
Name Type Description
Error number Critical error occurred.
Uninitialized number Client is created but not used yet.
ConnectingToNameServer number Connecting to NameServer.
ConnectedToNameServer number Connected to NameServer.
ConnectingToMasterserver number Connecting to Master (includes connect, authenticate and joining the lobby).
ConnectedToMaster number Connected to Master server.
JoinedLobby number Connected to Master and joined lobby. Display room list and join/create rooms at will.
ConnectingToGameserver number Connecting to Game server(client will authenticate and join/create game).
ConnectedToGameserver number Connected to Game server (going to auth and join game).
Joined number The client joined room.
Disconnected number The client is no longer connected (to any server). Connect to Master to go on.

Methods

actorFactory(name, actorNr, isLocal)

Override with creation of custom actor (extended from Actor): { return new CustomActor(...); }

Parameters:
Name Type Description
name string Actor name. Pass to super() in custom room constructor.
actorNr number Actor ID. Pass to super() in custom room constructor.
isLocal boolean Actor is local. Pass to super() in custom room constructor.

availableRooms() → {Array.<Photon.LoadBalancing.RoomInfo>}

Current room list from Master server.

Returns:
Current room list
Type
Array.<Photon.LoadBalancing.RoomInfo>

changeGroups(groupsToRemove, groupsToAdd)

Changes client's interest groups (for events in room).
Note the difference between passing null and []: null won't add/remove any groups, [] will add/remove all (existing) groups.
First, removing groups is executed. This way, you could leave all groups and join only the ones provided.

Parameters:
Name Type Description
groupsToRemove Array.<number> Groups to remove from interest. Null will not leave any. A [] will remove all.
groupsToAdd Array.<number> Groups to add to interest. Null will not add any. A [] will add all current.

connect(optionsopt) → {boolean}

Starts connection to Master server.

Parameters:
Name Type Attributes Description
options object <optional>
Additional options
Properties:
Name Type Description
options object Additional options
Properties
Name Type Attributes Default Description
keepMasterConnection boolean <optional>
false Don't disconnect from Master server after joining room.
lobbyName string <optional>
Name of the lobby connect to.
lobbyType Photon.LoadBalancing.Constants.LobbyType <optional>
LobbyType.Default Type of the lobby.
lobbyStats boolean <optional>
false If true, Master server will be sending lobbies statistics periodically.
Override onLobbyStats to handle request results.
Alternatively, requestLobbyStats can be used.
Returns:
True if current client state allows connection.
Type
boolean

connectToNameServer(optionsopt) → {boolean}

Starts connection to NameServer.

Parameters:
Name Type Attributes Description
options object <optional>
Additional options
Properties:
Name Type Description
options object Additional options
Properties
Name Type Attributes Default Description
region string <optional>
If specified, Connect to region master after succesfull connection to name server
lobbyName string <optional>
Name of the lobby connect to.
lobbyType Photon.LoadBalancing.Constants.LobbyType <optional>
LobbyType.Default Type of the lobby.
lobbyStats boolean <optional>
false If true, Master server will be sending lobbies statistics periodically.
Override onLobbyStats to handle request results.
Alternatively, requestLobbyStats can be used.
keepMasterConnection boolean <optional>
false Don't disconnect from Master server after joining room.
Returns:
True if current client state allows connection.
Type
boolean

connectToRegionMaster(region) → {boolean}

Connects to a specific region's Master server, using the NameServer to find the IP.

Parameters:
Name Type Description
region string Region connect to Master server of.
Returns:
True if current client state allows connection.
Type
boolean

createRoom(roomNameopt, optionsopt) → {boolean}

Creates a new room on the server (or fails when the name is already taken).

Parameters:
Name Type Attributes Description
roomName string <optional>
The name to create a room with. Must be unique and not in use or can't be created. If not specified or null, the server will assign a GUID as name.
options object <optional>
Additional options
Properties:
Name Type Description
options object Additional options
Properties
Name Type Attributes Default Description
isVisible boolean <optional>
true Shows the room in the lobby's room list.
isOpen boolean <optional>
true Keeps players from joining the room (or opens it to everyone).
maxPlayers number <optional>
0 Max players before room is considered full (but still listed).
customGameProperties object <optional>
Custom properties to apply to the room on creation (use string-typed keys but short ones).
propsListedInLobby Array.<string> <optional>
Defines the custom room properties that get listed in the lobby.
roomTTL number <optional>
0 Room Time To Live (ms) in the server room cache after all clients have left the room.
playerTTL number <optional>
0 Player Time To Live (ms) in the room after player suspended.
plugins Array.<string> <optional>
Expected server plugins.
lobbyName string <optional>
"" Name of the lobby to create room in.
lobbyType Photon.LoadBalancing.Constants.LobbyType <optional>
LobbyType.Default Type of the lobby.
expectedUsers Array.<string> <optional>
Expected users.
Returns:
True if current client state allows connection.
Type
boolean

createRoomFromMy(roomNameopt, optionsopt)

Creates a new room on the server (or fails when the name is already taken). Takes parameters (except name) for new room from myRoom() object. Set them before call.

Parameters:
Name Type Attributes Description
roomName string <optional>
New room name. Assigned automatically by server if empty or not specified.
options object <optional>
Additional options
Properties:
Name Type Description
options object Additional options
Properties
Name Type Attributes Default Description
lobbyName string <optional>
Name of the lobby to create room in.
lobbyType Photon.LoadBalancing.Constants.LobbyType <optional>
LobbyType.Default Type of the lobby.

disconnect()

Disconnects from all servers.

findFriends(friendsToFind)

Requests Master server for actors online status and joined rooms.
Override onFindFriendsResult to handle request results.

Parameters:
Name Type Description
friendsToFind Array.<string> Actors names.

getMasterServerAddress() → {string}

Returns current Master server address.

Returns:
Master server address.
Type
string

getNameServerAddress() → {string}

Returns current NameServer address.

Returns:
NameServer address address.
Type
string

getRegions()

Requests NameServer for regions list.
Override onGetRegionsResult to handle request results.

getRtt() → {number}

Returns the latest measurement of game server Round Trip Time.
RTT is measured once on connection and then on each updateRtt() call.

Returns:
Type
number

getServerTimeMs() → {number}

Returns game server time extrapolation in milliseconds based on the server time fetched on connection or on syncServerTime() call.
The server time is a signed 32 bit integer making a full cycle in 49.71 days.

Returns:
Type
number

getUserId() → {string}

Returns previously set user id.

Returns:
User id.
Type
string

isConnectedToMaster() → {boolean}

Checks if client is connected to Master server (usually joined to lobby and receives room list updates).

Returns:
True if client is connected to Master server.
Type
boolean

isConnectedToNameServer() → {boolean}

Checks if client is connected to NameServer server.

Returns:
True if client is connected to NameServer server.
Type
boolean

isInLobby() → {boolean}

Checks if client is in lobby and ready to join or create game.

Returns:
True if client is in lobby.
Type
boolean

isJoinedToRoom() → {boolean}

Checks if client is joined to game.

Returns:
True if client is joined to game.
Type
boolean

joinRandomOrCreateRoom(optionsopt, createRoomNameopt, createOptionsopt) → {boolean}

Attempts to join a room that matches the specified filter and creates a room if none found. This operation is a combination of filter-based random matchmaking with the option to create a new room, if no fitting room exists. The benefit of that is that the room creation is done by the same operation and the room can be found by the very next client, looking for similar rooms. There are separate parameters for joining and creating a room. This method can only be called while connected to a Master Server. This client's State is set to ClientState.Joining immediately. Either IMatchmakingCallbacks.OnJoinedRoom or IMatchmakingCallbacks.OnCreatedRoom get called. More about matchmaking: https://doc.photonengine.com/en-us/realtime/current/reference/matchmaking-and-lobby Check the return value to make sure the operation will be called on the server. Note: There will be no callbacks if this method returned false.

Parameters:
Name Type Attributes Description
options object <optional>
Additional join options
createRoomName string <optional>
New room name. Assigned automatically by server if empty or not specified.
createOptions object <optional>
Additional create options
Properties:
Name Type Description
options object Additional options
Properties
Name Type Attributes Default Description
expectedCustomRoomProperties object <optional>
If specified, a room will only be joined, if it matches these custom properties. Use null to accept rooms with any properties.
expectedMaxPlayers number <optional>
If specified, filters for a particular maxPlayer setting. Use 0 to accept any maxPlayer value.
matchmakingMode Photon.LoadBalancing.Constants.MatchmakingMode <optional>
MatchmakingMode.FillRoom Selects one of the available matchmaking algorithms.
lobbyName string <optional>
Name of the lobby to search rooms in.
lobbyType Photon.LoadBalancing.Constants.LobbyType <optional>
LobbyType.Default Type of the lobby.
sqlLobbyFilter string <optional>
Basically the "where" clause of a sql statement. Examples: 'C0 = 1 AND C2 > 50'. 'C5 = "Map2" AND C2 > 10 AND C2 < 20'
expectedUsers Array.<string> <optional>
Expected users.
createOptions object Additional create options
Properties
Name Type Attributes Default Description
isVisible boolean <optional>
true Shows the room in the lobby's room list.
isOpen boolean <optional>
true Keeps players from joining the room (or opens it to everyone).
maxPlayers number <optional>
0 Max players before room is considered full (but still listed).
customGameProperties object <optional>
Custom properties to apply to the room on creation (use string-typed keys but short ones).
propsListedInLobby Array.<string> <optional>
Defines the custom room properties that get listed in the lobby.
roomTTL number <optional>
0 Room Time To Live (ms) in the server room cache after all clients have left the room.
playerTTL number <optional>
0 Player Time To Live (ms) in the room after player suspended.
plugins Array.<string> <optional>
Expected server plugins.
Returns:
If the operation will be sent (requires connection to Master Server).
Type
boolean

joinRandomRoom(optionsopt) → {boolean}

Joins a random, available room. This operation fails if all rooms are closed or full.

Parameters:
Name Type Attributes Description
options object <optional>
Additional options
Properties:
Name Type Description
options object Additional options
Properties
Name Type Attributes Default Description
expectedCustomRoomProperties object <optional>
If specified, a room will only be joined, if it matches these custom properties. Use null to accept rooms with any properties.
expectedMaxPlayers number <optional>
If specified, filters for a particular maxPlayer setting. Use 0 to accept any maxPlayer value.
matchmakingMode Photon.LoadBalancing.Constants.MatchmakingMode <optional>
MatchmakingMode.FillRoom Selects one of the available matchmaking algorithms.
lobbyName string <optional>
Name of the lobby to search rooms in.
lobbyType Photon.LoadBalancing.Constants.LobbyType <optional>
LobbyType.Default Type of the lobby.
sqlLobbyFilter string <optional>
Basically the "where" clause of a sql statement. Examples: 'C0 = 1 AND C2 > 50'. 'C5 = "Map2" AND C2 > 10 AND C2 < 20'
expectedUsers Array.<string> <optional>
Expected users.
Returns:
If the operation will be sent (requires connection to Master Server).
Type
boolean

joinRoom(roomName, optionsopt, createOptionsopt) → {boolean}

Joins a room by name and sets this player's properties.

Parameters:
Name Type Attributes Description
roomName string The name of the room to join. Must be existing already, open and non-full or can't be joined.
options object <optional>
Additional options
createOptions object <optional>
Room options for creation
Properties:
Name Type Description
options object Additional options
Properties
Name Type Attributes Default Description
rejoin boolean <optional>
false Rejoin using current userId.
createIfNotExists boolean <optional>
false Create room if not exists.
expectedUsers Array.<string> <optional>
Expected users.
createOptions object Room options for creation
Properties
Name Type Attributes Default Description
isVisible boolean <optional>
true Shows the room in the lobby's room list.
isOpen boolean <optional>
true Keeps players from joining the room (or opens it to everyone).
maxPlayers number <optional>
0 Max players before room is considered full (but still listed).
customGameProperties object <optional>
Custom properties to apply to the room on creation (use string-typed keys but short ones).
propsListedInLobby Array.<string> <optional>
Defines the custom room properties that get listed in the lobby.
roomTTL number <optional>
0 Room Time To Live (ms) in the server room cache after all clients have left the room.
playerTTL number <optional>
0 Player Time To Live (ms) in the room after player suspended.
plugins Array.<string> <optional>
Informs the server of the expected plugin setup.
lobbyName string <optional>
"" Name of the lobby to create room in.
lobbyType Photon.LoadBalancing.Constants.LobbyType <optional>
LobbyType.Default Type of the lobby.
Returns:
If the operation will be sent (requires connection to Master Server).
Type
boolean

leaveRoom()

Leaves room and connects to Master server if not connected.

Properties:
Name Type Description
options object Additional options
Properties
Name Type Attributes Description
sendAuthCookie boolean <optional>
Securely transmit the encrypted object AuthCookie to the web service in PathLeave webhook when available

myActor() → {Photon.LoadBalancing.Actor}

Returns local actor. Client always has local actor even if not joined.

Returns:
Local actor.
Type
Photon.LoadBalancing.Actor

myRoom() → {Photon.LoadBalancing.Room}

Returns client's room. Client always has it's room even if not joined. It's used for room creation operation.

Returns:
Current room.
Type
Photon.LoadBalancing.Room

myRoomActorCount() → {number}

Returns numer of actors in room client currently joined including local actor.

Returns:
Number of actors.
Type
number

myRoomActors() → {object}

Returns actors in room client currently joined including local actor.

Returns:
actorNr -> Photon.LoadBalancing.Actor map of actors in room.
Type
object

myRoomMasterActorNr() → {number}

Actor number of the player who's the master of this Room. Note: This changes when the current master leaves the room.

Returns:
Type
number

onActorJoin(actor)

Called when new actor joins the room client joined to. Override to handle it.

Parameters:
Name Type Description
actor Photon.LoadBalancing.Actor New actor.

onActorLeave(actor, cleanup)

Called when actor leaves the room client joined to. Also called for every actor during room cleanup. Override to handle it.

Parameters:
Name Type Description
actor Photon.LoadBalancing.Actor Actor left the room.
cleanup boolean True if called during room cleanup (e.g. on disconnect).

onActorPropertiesChange(actor)

Called on actor properties changed event. Override to handle it.

Parameters:
Name Type Description
actor Photon.LoadBalancing.Actor Actor whose properties were changed.

onActorSuspend(actor)

Called when actor suspended in the room client joined to.Override to handle it.

Parameters:
Name Type Description
actor Photon.LoadBalancing.Actor Actor suspended in the room.

onAppStats(errorCode, errorMsg, stats)

Called when application statistics update received.
Override to handle request results.

Parameters:
Name Type Description
errorCode number Result error code. Currently is always 0.
errorMsg string Error message. Currently is always empty.
stats object Application statistics.
Properties:
Name Type Description
stats object Application statistics.
Properties
Name Type Description
peerCount number Count of players currently online on Game servers.
masterPeerCount number Count of players on Master server (looking for game).
gameCount number Count of games currently in use (includes invisible and full rooms, so it doesn't match lobby list).

onError(errorCode, errorMsg)

Called if client error occures. Override to handle it.

Parameters:
Name Type Description
errorCode Photon.LoadBalancing.LoadBalancingClient.PeerErrorCode Client error code.
errorMsg string Error message.

onEvent(code, content, actorNr)

Called on custom event. Override to handle it.

Parameters:
Name Type Description
code number Event code.
content object Event content.
actorNr number Actor ID event raised by.

onFindFriendsResult(errorCode, errorMsg, friends)

Called when findFriends request completed.
Override to handle request results.

Parameters:
Name Type Description
errorCode number Result error code. 0 if request is successful.
errorMsg string Error message.
friends object Table with actors names as keys and friend statuses as values: {name1: friendStatus1, name2: friendStatus2, ... }.
Properties:
Name Type Description
friendStatus object Friend status.
Properties
Name Type Description
online boolean Online status.
roomId string Joined room.

onJoinRoom(createdByMe)

Called when client joins room. Override to handle it.

Parameters:
Name Type Description
createdByMe boolean True if room is created by client.

onLobbyStats(errorCode, errorMsg, lobbies)

Called when lobbies statistics update received.
Update can be automated by set up during connect or requested explicitly by requestLobbyStats.
Override to handle request results.

Parameters:
Name Type Description
errorCode number Result error code. 0 if request is successful. For automated updates is always 0.
errorMsg string Error message. For automated updates is always empty.
lobbies Array.<object> Array of lobbies statistics: [lobbyStats1, lobbyStats1, ... ].
Properties:
Name Type Description
lobbyStats object Lobby statistics.
Properties
Name Type Description
lobbyName string Lobby name.
lobbyType number Lobby type.
peerCount number The number of players in the lobby (on Master, not playing).
gameCount number The number of games in the lobby.

onMyRoomPropertiesChange()

Called on joined room properties changed event. Override to handle it.

onOperationResponse(errorCode, errorMsg, code, content)

Called on operation response. Override if need custom workflow or response error handling.

Parameters:
Name Type Description
errorCode number Server error code.
errorMsg string Error message.
code number Operation code.
content object Operation response content.

onRoomList(rooms)

Called on room list received from Master server (on connection). Override to handle it.

Parameters:
Name Type Description
rooms Array.<Photon.LoadBalancing.RoomInfo> Room list.

onRoomListUpdate(rooms, roomsUpdated, roomsAdded, roomsRemoved)

Called on room list updates received from Master server. Override to handle it.

Parameters:
Name Type Description
rooms Array.<Photon.LoadBalancing.RoomInfo> Updated room list.
roomsUpdated Array.<Photon.LoadBalancing.RoomInfo> Rooms whose properties were changed.
roomsAdded Array.<Photon.LoadBalancing.RoomInfo> New rooms in list.
roomsRemoved Array.<Photon.LoadBalancing.RoomInfo> Rooms removed from list.

onServerErrorInfo(info)

Called when the server reports non-critical error.
Override to handle the event.

In most cases this could be either:
1. an error from webhooks plugin (if HasErrorInfo is enabled), read more
2. an error sent from a custom server plugin via PluginHost.BroadcastErrorInfoEvent, see example
3. an error sent from the server, for example, when the limit of cached events has been exceeded in the room (all clients will be disconnected and the room will be closed in this case), read more
Parameters:
Name Type Description
info string Error info.

onStateChange(state)

Called on client state change. Override to handle it.

Parameters:
Name Type Description
state Photon.LoadBalancing.LoadBalancingClient.State New client state.

onWebRpcResult(errorCode, message, uriPath, resultCode, data)

Called when webRpc request completed.
Override to handle request results.

Parameters:
Name Type Description
errorCode number Result error code. 0 if request is successful.
message string Error message if errorCode ~ = 0 or optional message returned by remote procedure.
uriPath string Request path.
resultCode number Result code returned by remote procedure.
data object Data returned by remote procedure.

raiseEvent(eventCode, dataopt, optionsopt)

Raises game custom event

Parameters:
Name Type Attributes Description
eventCode number Identifies this type of event (and the content). Your game's event codes can start with 0.
data object <optional>
Custom data you want to send along (use null, if none).
options object <optional>
Additional options
Properties:
Name Type Description
options object Additional options
Properties
Name Type Attributes Default Description
interestGroup number <optional>
The ID of the interest group this event goes to (exclusively).
cache Photon.LoadBalancing.Constants.EventCaching <optional>
EventCaching.DoNotCache Events can be cached (merged and removed) for players joining later on.
receivers Photon.LoadBalancing.Constants.ReceiverGroup <optional>
ReceiverGroup.Others Defines to which group of players the event is passed on.
targetActors Array.<number> <optional>
Defines the target players who should receive the event (use only for small target groups).
webForward boolean <optional>
false Forward to web hook.

reconnectToMaster() → {boolean}

Can be used to reconnect to the master server after a disconnect. Common use case: Press the Lock Button on a iOS device and you get disconnected immediately

Returns:
True if current client state allows reconnection.
Type
boolean

reconnectToMaster() → {boolean}

Can be used to return to a room quickly by directly reconnecting to a game server to rejoin a room. Rejoining room will not send any player properties. Instead client will receive up-to-date ones from server. If you want to set new player properties, do it once rejoined.

Returns:
True if current client state allows reconnection.
Type
boolean

requestLobbyStats(lobbiesToRequest)

Requests Master server for lobbies statistics.
Override onLobbyStats to handle request results.
Alternatively, automated updates can be set up during connect.

Parameters:
Name Type Description
lobbiesToRequest Array.<any> Array of lobbies id pairs [ [lobbyName1, lobbyType1], [lobbyName2, lobbyType2], ... ]. If not specified or null, statistics for all lobbies requested.

roomFactory(name)

Override with creation of custom room (extended from Room): { return new CustomRoom(...); }

Parameters:
Name Type Description
name string Room name. Pass to super() in custom actor constructor.

setAppId(appId)

Changes application id.

Parameters:
Name Type Description
appId string New address and port.

setAppVersion(appVersion)

Changes application version.

Parameters:
Name Type Description
appVersion string New address and port.

setCustomAuthentication(authParameters, authTypeopt, authDataopt)

Enables custom authentication and sets it's parameters.

Parameters:
Name Type Attributes Default Description
authParameters string This string must contain any (http get) parameters expected by the used authentication service.
authType Photon.LoadBalancing.Constants.CustomAuthenticationType <optional>
Photon.LoadBalancing.Constants.CustomAuthenticationType.Custom The type of custom authentication provider that should be used.
authData any <optional>
The data to be passed-on to the auth service via POST. String passed as is, objects as application/json

setLogLevel(level)

Sets client log level

Parameters:
Name Type Description
level Photon.LogLevel Log level.

setMasterServerAddress(address)

Changes default Master server address and port before connecting to Master server.

Parameters:
Name Type Description
address string New address and port.

setNameServerAddress(address)

Changes default NameServer address and port before connecting to NameServer.

Parameters:
Name Type Description
address string New address and port.

setUserId(userId)

Sets user ID required for authentication and FindFriends service. The value will be used the next time you connect. Set this ID before you connect, not while being connected.

Parameters:
Name Type Description
userId string New user id.

state() → {number}

Returns the current client state.

Returns:
{Photon.LoadBalancingClient.State} member.
Type
number

suspendRoom()

Disconnects client from Game server keeping player in room (to rejoin later) and connects to Master server if not connected.

Properties:
Name Type Description
options object Additional options
Properties
Name Type Attributes Description
sendAuthCookie boolean <optional>
Securely transmit the encrypted object AuthCookie to the web service in PathLeave webhook when available

syncServerTime()

Fetches server time from the game server and updates the base value used for extrapolation in getServerTimeMs().

updateRtt()

Triggers game server Round Trip Time measurement.

webRpc(uriPath, parameters, optionsopt)

Sends web rpc request to Master server.
Override onWebRpcResult to handle request results.

Parameters:
Name Type Attributes Description
uriPath string Request path.
parameters object Request parameters.
options object <optional>
Additional options
Properties:
Name Type Description
options object Additional options
Properties
Name Type Attributes Description
sendAuthCookie boolean <optional>
Defines if the authentication cookie gets sent to a WebHook (if setup)

(static) StateToName(state) → {string}

Converts State element to string name.

Parameters:
Name Type Description
state Photon.LoadBalancing.LoadBalancingClient.State Client state enum element.
Returns:
Specified element name or undefined if not found.
Type
string