Photon Unity Networking 2  2.9
English | 日本語 | 한국
Public Member Functions | Public Attributes | Properties | Events | List of all members
LoadBalancingClient Class Reference

This class implements the Photon LoadBalancing workflow by using a LoadBalancingPeer. It keeps a state and will automatically execute transitions between the Master and Game Servers. More...

Inherits IPhotonPeerListener.

Public Member Functions

 LoadBalancingClient (ConnectionProtocol protocol=ConnectionProtocol.Udp)
 Creates a LoadBalancingClient with UDP protocol or the one specified. More...
 
 LoadBalancingClient (string masterAddress, string appId, string gameVersion, ConnectionProtocol protocol=ConnectionProtocol.Udp)
 Creates a LoadBalancingClient, setting various values needed before connecting. More...
 
virtual bool Connect ()
 Starts the "process" to connect to a Master Server, using MasterServerAddress and AppId properties. More...
 
bool ConnectToNameServer ()
 Connects to the NameServer for Photon Cloud, where a region and server list can be obtained. More...
 
bool ConnectToRegionMaster (string region)
 Connects you to a specific region's Master Server, using the Name Server to find the IP. More...
 
bool ReconnectToMaster ()
 Can be used to reconnect to the master server after a disconnect. More...
 
bool ReconnectAndRejoin ()
 Can be used to return to a room quickly, by directly reconnecting to a game server to rejoin a room. More...
 
void Disconnect ()
 Disconnects this client from any server and sets this.State if the connection is successfuly closed. More...
 
void Service ()
 This method dispatches all available incoming commands and then sends this client's outgoing commands. It uses DispatchIncomingCommands and SendOutgoingCommands to do that. More...
 
bool OpFindFriends (string[] friendsToFind)
 Request the rooms and online status for a list of friends. All clients should set a unique UserId before connecting. The result is available in this.FriendList. More...
 
bool OpJoinLobby (TypedLobby lobby)
 If already connected to a Master Server, this joins the specified lobby. This request triggers an OnOperationResponse() call and the callback OnJoinedLobby(). More...
 
bool OpLeaveLobby ()
 Opposite of joining a lobby. You don't have to explicitly leave a lobby to join another (client can be in one max, at any time). More...
 
bool OpJoinRandomRoom (OpJoinRandomRoomParams opJoinRandomRoomParams=null)
 Joins a random room that matches the filter. Will callback: OnJoinedRoom or OnJoinRandomFailed. More...
 
bool OpCreateRoom (EnterRoomParams enterRoomParams)
 Creates a new room. Will callback: OnCreatedRoom and OnJoinedRoom or OnCreateRoomFailed. More...
 
bool OpJoinOrCreateRoom (EnterRoomParams enterRoomParams)
 Joins a specific room by name and creates it on demand. Will callback: OnJoinedRoom or OnJoinRoomFailed. More...
 
bool OpJoinRoom (EnterRoomParams enterRoomParams)
 Joins a room by name. Will callback: OnJoinedRoom or OnJoinRoomFailed. More...
 
bool OpRejoinRoom (string roomName)
 Rejoins a room by roomName (using the userID internally to return). Will callback: OnJoinedRoom or OnJoinRoomFailed. More...
 
bool OpLeaveRoom (bool becomeInactive, bool sendAuthCookie=false)
 Leaves the current room, optionally telling the server that the user is just becoming inactive. Will callback: OnLeftRoom. More...
 
bool OpGetGameList (TypedLobby typedLobby, string sqlLobbyFilter)
 Gets a list of games matching a SQL-like where clause. More...
 
bool OpSetCustomPropertiesOfActor (int actorNr, Hashtable propertiesToSet, Hashtable expectedProperties=null, WebFlags webFlags=null)
 Updates and synchronizes a Player's Custom Properties. Optionally, expectedProperties can be provided as condition. More...
 
bool OpSetCustomPropertiesOfRoom (Hashtable propertiesToSet, Hashtable expectedProperties=null, WebFlags webFlags=null)
 Updates and synchronizes this Room's Custom Properties. Optionally, expectedProperties can be provided as condition. More...
 
bool OpSetPropertiesOfRoom (Hashtable gameProperties, Hashtable expectedProperties=null, WebFlags webFlags=null)
 Internally used to cache and set properties (including well known properties). More...
 
virtual bool OpRaiseEvent (byte eventCode, object customEventContent, RaiseEventOptions raiseEventOptions, SendOptions sendOptions)
 Send an event with custom code/type and any content to the other players in the same room. More...
 
virtual bool OpChangeGroups (byte[] groupsToRemove, byte[] groupsToAdd)
 Operation to handle this client's interest groups (for events in room). More...
 
void ChangeLocalID (int newID)
 Internally used to set the LocalPlayer's ID (from -1 to the actual in-room ID). More...
 
virtual void DebugReturn (DebugLevel level, string message)
 Debug output of low level api (and this client). More...
 
virtual void OnOperationResponse (OperationResponse operationResponse)
 Uses the OperationResponses provided by the server to advance the internal state and call ops as needed. More...
 
virtual void OnStatusChanged (StatusCode statusCode)
 Uses the connection's statusCodes to advance the internal state and call operations as needed. More...
 
virtual void OnEvent (EventData photonEvent)
 Uses the photonEvent's provided by the server to advance the internal state and call ops as needed. More...
 
virtual void OnMessage (object message)
 In Photon 4, "raw messages" will get their own callback method in the interface. Not used yet. More...
 
bool OpWebRpc (string uriPath, object parameters, bool sendAuthCookie=false)
 This operation makes Photon call your custom web-service by path/name with the given parameters (converted into Json). More...
 
void AddCallbackTarget (object target)
 Registers an object for callbacks for the implemented callback-interfaces. More...
 
void RemoveCallbackTarget (object target)
 Unregisters an object from callbacks for the implemented callback-interfaces. More...
 

Public Attributes

AuthModeOption AuthMode = AuthModeOption.Auth
 Enables the new Authentication workflow. More...
 
EncryptionMode EncryptionMode = EncryptionMode.PayloadEncryption
 Defines how the communication gets encrypted. More...
 
ConnectionProtocol ExpectedProtocol = ConnectionProtocol.Udp
 The protocol which will be used on Master- and Gameserver. More...
 
string NameServerHost = "ns.exitgames.com"
 Name Server Host Name for Photon Cloud. Without port and without any prefix. More...
 
string NameServerHttp = "http://ns.exitgames.com:80/photon/n"
 Name Server for HTTP connections to the Photon Cloud. Includes prefix and port. More...
 
ConnectionCallbacksContainer ConnectionCallbackTargets = new ConnectionCallbacksContainer()
 Wraps up the target objects for a group of callbacks, so they can be called conveniently. More...
 
MatchMakingCallbacksContainer MatchMakingCallbackTargets = new MatchMakingCallbacksContainer()
 Wraps up the target objects for a group of callbacks, so they can be called conveniently. More...
 
bool EnableLobbyStatistics
 If enabled, the client will get a list of available lobbies from the Master Server. More...
 
RegionHandler RegionHandler
 Contains the list if enabled regions this client may use. Null, unless the client got a response to OpGetRegions. More...
 

Properties

LoadBalancingPeer LoadBalancingPeer [get, set]
 The client uses a LoadBalancingPeer as API to communicate with the server. This is public for ease-of-use: Some methods like OpRaiseEvent are not relevant for the connection state and don't need a override. More...
 
string AppVersion [get, set]
 The version of your client. A new version also creates a new "virtual app" to separate players from older client versions. More...
 
string AppId [get, set]
 The AppID as assigned from the Photon Cloud. If you host yourself, this is the "regular" Photon Server Application Name (most likely: "LoadBalancing"). More...
 
AuthenticationValues AuthValues [get, set]
 User authentication values to be sent to the Photon server right after connecting. More...
 
bool IsUsingNameServer [get, set]
 True if this client uses a NameServer to get the Master Server address. More...
 
string NameServerAddress [get]
 Name Server Address for Photon Cloud (based on current protocol). You can use the default values and usually won't have to set this value. More...
 
bool UseAlternativeUdpPorts [get, set]
 Use the alternative ports for UDP connections in the Public Cloud (27000 to 27003). More...
 
string CurrentServerAddress [get]
 The currently used server address (if any). The type of server is define by Server property. More...
 
string MasterServerAddress [get, set]
 Your Master Server address. In PhotonCloud, call ConnectToRegionMaster() to find your Master Server. More...
 
string GameServerAddress [get, set]
 The game server's address for a particular room. In use temporarily, as assigned by master. More...
 
ServerConnection Server [get, set]
 The server this client is currently connected or connecting to. More...
 
ClientState State [get, set]
 Current state this client is in. Careful: several states are "transitions" that lead to other states. More...
 
bool IsConnected [get]
 Returns if this client is currently connected or connecting to some type of server. More...
 
bool IsConnectedAndReady [get]
 A refined version of IsConnected which is true only if your connection is ready to send operations. More...
 
DisconnectCause DisconnectedCause [get, set]
 Summarizes (aggregates) the different causes for disconnects of a client. More...
 
bool InLobby [get, set]
 Internal value if the client is in a lobby. More...
 
TypedLobby CurrentLobby [get, set]
 The lobby this client currently uses. Defined when joining a lobby or creating rooms More...
 
Player LocalPlayer [get, set]
 The local player is never null but not valid unless the client is in a room, too. The ID will be -1 outside of rooms. More...
 
string NickName [get, set]
 The nickname of the player (synced with others). Same as client.LocalPlayer.NickName. More...
 
string UserId [get, set]
 An ID for this user. Sent in OpAuthenticate when you connect. If not set, the PlayerName is applied during connect. More...
 
Room CurrentRoom [get, set]
 The current room this client is connected to (null if none available). More...
 
bool InRoom [get]
 Is true while being in a room (this.state == ClientState.Joined). More...
 
int PlayersOnMasterCount [get, set]
 Statistic value available on master server: Players on master (looking for games). More...
 
int PlayersInRoomsCount [get, set]
 Statistic value available on master server: Players in rooms (playing). More...
 
int RoomsCount [get, set]
 Statistic value available on master server: Rooms currently created. More...
 
bool IsFetchingFriendList [get]
 Internal flag to know if the client currently fetches a friend list. More...
 
string CloudRegion [get, set]
 The cloud region this client connects to. Set by ConnectToRegionMaster(). Not set if you don't use a NameServer! More...
 

Events

Action< ClientState, ClientStateStateChanged
 Register a method to be called when this client's ClientState gets set. More...
 
Action< EventData > EventReceived
 Register a method to be called when an event got dispatched. Gets called after the LoadBalancingClient handled the internal events first. More...
 
Action< OperationResponse > OpResponseReceived
 Register a method to be called when an operation response is received. More...
 

Detailed Description

This class implements the Photon LoadBalancing workflow by using a LoadBalancingPeer. It keeps a state and will automatically execute transitions between the Master and Game Servers.

This class (and the Player class) should be extended to implement your own game logic. You can override CreatePlayer as "factory" method for Players and return your own Player instances. The State of this class is essential to know when a client is in a lobby (or just on the master) and when in a game where the actual gameplay should take place. Extension notes: An extension of this class should override the methods of the IPhotonPeerListener, as they are called when the state changes. Call base.method first, then pick the operation or state you want to react to and put it in a switch-case. We try to provide demo to each platform where this api can be used, so lookout for those.

Constructor & Destructor Documentation

LoadBalancingClient ( ConnectionProtocol  protocol = ConnectionProtocol.Udp)

Creates a LoadBalancingClient with UDP protocol or the one specified.

Parameters
protocolSpecifies the network protocol to use for connections.
LoadBalancingClient ( string  masterAddress,
string  appId,
string  gameVersion,
ConnectionProtocol  protocol = ConnectionProtocol.Udp 
)

Creates a LoadBalancingClient, setting various values needed before connecting.

Parameters
masterAddressThe Master Server's address to connect to. Used in Connect.
appIdThe AppId of this title. Needed for the Photon Cloud. Find it in the Dashboard.
gameVersionA version for this client/build. In the Photon Cloud, players are separated by AppId, GameVersion and Region.
protocolSpecifies the network protocol to use for connections.

Member Function Documentation

void AddCallbackTarget ( object  target)

Registers an object for callbacks for the implemented callback-interfaces.

The covered callback interfaces are: IConnectionCallbacks, IMatchmakingCallbacks, ILobbyCallbacks, IInRoomCallbacks, IOnEventCallback and IWebRpcCallback.

See: The object that registers to get callbacks from this client.

void ChangeLocalID ( int  newID)

Internally used to set the LocalPlayer's ID (from -1 to the actual in-room ID).

Parameters
newIDNew actor ID (a.k.a actorNr) assigned when joining a room.
virtual bool Connect ( )
virtual

Starts the "process" to connect to a Master Server, using MasterServerAddress and AppId properties.

To connect to the Photon Cloud, use ConnectToRegionMaster().

The process to connect includes several steps: the actual connecting, establishing encryption, authentification (of app and optionally the user) and connecting to the MasterServer

Users can connect either anonymously or use "Custom Authentication" to verify each individual player's login. Custom Authentication in Photon uses external services and communities to verify users. While the client provides a user's info, the service setup is done in the Photon Cloud Dashboard. The parameter authValues will set this.AuthValues and use them in the connect process.

Connecting to the Photon Cloud might fail due to:

bool ConnectToNameServer ( )

Connects to the NameServer for Photon Cloud, where a region and server list can be obtained.

OpGetRegions

Returns
If the workflow was started or failed right away.
bool ConnectToRegionMaster ( string  region)

Connects you to a specific region's Master Server, using the Name Server to find the IP.

Returns
If the operation could be sent. If false, no operation was sent.
virtual void DebugReturn ( DebugLevel  level,
string  message 
)
virtual

Debug output of low level api (and this client).

This method is not responsible to keep up the state of a LoadBalancingClient. Calling base.DebugReturn on overrides is optional.

void Disconnect ( )

Disconnects this client from any server and sets this.State if the connection is successfuly closed.

virtual void OnEvent ( EventData  photonEvent)
virtual

Uses the photonEvent's provided by the server to advance the internal state and call ops as needed.

This method is essential to update the internal state of a LoadBalancingClient. Overriding methods must call base.OnEvent.

virtual void OnMessage ( object  message)
virtual

In Photon 4, "raw messages" will get their own callback method in the interface. Not used yet.

virtual void OnOperationResponse ( OperationResponse  operationResponse)
virtual

Uses the OperationResponses provided by the server to advance the internal state and call ops as needed.

When this method finishes, it will call your OnOpResponseAction (if any). This way, you can get any operation response without overriding this class.

To implement a more complex game/app logic, you should implement your own class that inherits the LoadBalancingClient. Override this method to use your own operation-responses easily.

This method is essential to update the internal state of a LoadBalancingClient, so overriding methods must call base.OnOperationResponse().

Parameters
operationResponseContains the server's response for an operation called by this peer.
virtual void OnStatusChanged ( StatusCode  statusCode)
virtual

Uses the connection's statusCodes to advance the internal state and call operations as needed.

This method is essential to update the internal state of a LoadBalancingClient. Overriding methods must call base.OnStatusChanged.

virtual bool OpChangeGroups ( byte[]  groupsToRemove,
byte[]  groupsToAdd 
)
virtual

Operation to handle this client's interest groups (for events in room).

Note the difference between passing null and byte[0]: null won't add/remove any groups. byte[0] will add/remove all (existing) groups. First, removing groups is executed. This way, you could leave all groups and join only the ones provided.

Changes become active not immediately but when the server executes this operation (approximately RTT/2).

Parameters
groupsToRemoveGroups to remove from interest. Null will not remove any. A byte[0] will remove all.
groupsToAddGroups to add to interest. Null will not add any. A byte[0] will add all current.
Returns
If operation could be enqueued for sending. Sent when calling: Service or SendOutgoingCommands.
bool OpCreateRoom ( EnterRoomParams  enterRoomParams)

Creates a new room. Will callback: OnCreatedRoom and OnJoinedRoom or OnCreateRoomFailed.

When successful, the client will enter the specified room and callback both OnCreatedRoom and OnJoinedRoom. In all error cases, OnCreateRoomFailed gets called.

Creating a room will fail if the room name is already in use or when the RoomOptions clashing with one another. Check the EnterRoomParams reference for the various room creation options.

This method can only be called while the client is connected to a Master Server so you should implement the callback OnConnectedToMaster. 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.

When you're in the room, this client's State will become ClientState.Joined.

When entering a room, this client's Player Custom Properties will be sent to the room. Use LocalPlayer.SetCustomProperties to set them, even while not yet in the room. Note that the player properties will be cached locally and are not wiped when leaving a room.

You can define an array of expectedUsers, to block player slots in the room for these users. The corresponding feature in Photon is called "Slot Reservation" and can be found in the doc pages.

Parameters
enterRoomParamsDefinition of properties for the room to create.
Returns
If the operation could be sent currently (requires connection to Master Server).
bool OpFindFriends ( string[]  friendsToFind)

Request the rooms and online status for a list of friends. All clients should set a unique UserId before connecting. The result is available in this.FriendList.

Used on Master Server to find the rooms played by a selected list of users. The result will be stored in LoadBalancingClient.FriendList, which is null before the first server response.

Users identify themselves by setting a UserId in the LoadBalancingClient instance. This will send the ID in OpAuthenticate during connect (to master and game servers). Note: Changing a player's name doesn't make sense when using a friend list.

The list of usernames must be fetched from some other source (not provided by Photon).

Internal: The server response includes 2 arrays of info (each index matching a friend from the request): ParameterCode.FindFriendsResponseOnlineList = bool[] of online states ParameterCode.FindFriendsResponseRoomIdList = string[] of room names (empty string if not in a room)

Parameters
friendsToFindArray of friend's names (make sure they are unique).
Returns
If the operation could be sent (requires connection).
bool OpGetGameList ( TypedLobby  typedLobby,
string  sqlLobbyFilter 
)

Gets a list of games matching a SQL-like where clause.

Operation is only available for lobbies of type SqlLobby. This is an async request which triggers a OnOperationResponse() call.

https://doc.photonengine.com/en-us/realtime/current/reference/matchmaking-and-lobby::sql_lobby_type

Parameters
typedLobbyThe lobby to query. Has to be of type SqlLobby.
sqlLobbyFilterThe sql query statement.
Returns
If the operation could be sent (has to be connected).
bool OpJoinLobby ( TypedLobby  lobby)

If already connected to a Master Server, this joins the specified lobby. This request triggers an OnOperationResponse() call and the callback OnJoinedLobby().

Parameters
lobbyThe lobby to join. Use null for default lobby.
Returns
If the operation could be sent. False, if the client is not IsConnectedAndReady or when it's not connected to a Master Server.
bool OpJoinOrCreateRoom ( EnterRoomParams  enterRoomParams)

Joins a specific room by name and creates it on demand. Will callback: OnJoinedRoom or OnJoinRoomFailed.

Useful when players make up a room name to meet in: All involved clients call the same method and whoever is first, also creates the room.

When successful, the client will enter the specified room. The client which creates the room, will callback both OnCreatedRoom and OnJoinedRoom. Clients that join an existing room will only callback OnJoinedRoom. In all error cases, OnJoinRoomFailed gets called.

Joining a room will fail, if the room is full, closed or when the user already is present in the room (checked by userId).

To return to a room, use OpRejoinRoom.

This method can only be called while the client is connected to a Master Server so you should implement the callback OnConnectedToMaster. 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.

This client's State is set to ClientState.Joining immediately, when the operation could be called. In the background, the client will switch servers and call various related operations.

When you're in the room, this client's State will become ClientState.Joined.

If you set room properties in roomOptions, they get ignored when the room is existing already. This avoids changing the room properties by late joining players.

When entering a room, this client's Player Custom Properties will be sent to the room. Use LocalPlayer.SetCustomProperties to set them, even while not yet in the room. Note that the player properties will be cached locally and are not wiped when leaving a room.

You can define an array of expectedUsers, to block player slots in the room for these users. The corresponding feature in Photon is called "Slot Reservation" and can be found in the doc pages.

Parameters
enterRoomParamsDefinition of properties for the room to create or join.
Returns
If the operation could be sent currently (requires connection to Master Server).
bool OpJoinRandomRoom ( OpJoinRandomRoomParams  opJoinRandomRoomParams = null)

Joins a random room that matches the filter. Will callback: OnJoinedRoom or OnJoinRandomFailed.

Used for random matchmaking. You can join any room or one with specific properties defined in opJoinRandomRoomParams.

You can use expectedCustomRoomProperties and expectedMaxPlayers as filters for accepting rooms. If you set expectedCustomRoomProperties, a room must have the exact same key values set at Custom Properties. You need to define which Custom Room Properties will be available for matchmaking when you create a room. See: OpCreateRoom(string roomName, RoomOptions roomOptions, TypedLobby lobby)

This operation fails if no rooms are fitting or available (all full, closed or not visible). It may also fail when actually joining the room which was found. Rooms may close, become full or empty anytime.

This method can only be called while the client is connected to a Master Server so you should implement the callback OnConnectedToMaster. 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.

This client's State is set to ClientState.Joining immediately, when the operation could be called. In the background, the client will switch servers and call various related operations.

When you're in the room, this client's State will become ClientState.Joined.

When entering a room, this client's Player Custom Properties will be sent to the room. Use LocalPlayer.SetCustomProperties to set them, even while not yet in the room. Note that the player properties will be cached locally and are not wiped when leaving a room.

More about matchmaking: https://doc.photonengine.com/en-us/realtime/current/reference/matchmaking-and-lobby

You can define an array of expectedUsers, to block player slots in the room for these users. The corresponding feature in Photon is called "Slot Reservation" and can be found in the doc pages.

Parameters
opJoinRandomRoomParamsOptional definition of properties to filter rooms in random matchmaking.
Returns
If the operation could be sent currently (requires connection to Master Server).
bool OpJoinRoom ( EnterRoomParams  enterRoomParams)

Joins a room by name. Will callback: OnJoinedRoom or OnJoinRoomFailed.

Useful when using lobbies or when players follow friends or invite each other.

When successful, the client will enter the specified room and callback via OnJoinedRoom. In all error cases, OnJoinRoomFailed gets called.

Joining a room will fail if the room is full, closed, not existing or when the user already is present in the room (checked by userId).

To return to a room, use OpRejoinRoom. When players invite each other and it's unclear who's first to respond, use OpJoinOrCreateRoom instead.

This method can only be called while the client is connected to a Master Server so you should implement the callback OnConnectedToMaster. 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.

A room's name has to be unique (per region, appid and gameversion). When your title uses a global matchmaking or invitations (e.g. an external solution), keep regions and the game versions in mind to join a room.

This client's State is set to ClientState.Joining immediately, when the operation could be called. In the background, the client will switch servers and call various related operations.

When you're in the room, this client's State will become ClientState.Joined.

When entering a room, this client's Player Custom Properties will be sent to the room. Use LocalPlayer.SetCustomProperties to set them, even while not yet in the room. Note that the player properties will be cached locally and are not wiped when leaving a room.

You can define an array of expectedUsers, to reserve player slots in the room for friends or party members. The corresponding feature in Photon is called "Slot Reservation" and can be found in the doc pages.

Parameters
enterRoomParamsDefinition of properties for the room to join.
Returns
If the operation could be sent currently (requires connection to Master Server).
bool OpLeaveLobby ( )

Opposite of joining a lobby. You don't have to explicitly leave a lobby to join another (client can be in one max, at any time).

Returns
If the operation could be sent (has to be connected).
bool OpLeaveRoom ( bool  becomeInactive,
bool  sendAuthCookie = false 
)

Leaves the current room, optionally telling the server that the user is just becoming inactive. Will callback: OnLeftRoom.

OpLeaveRoom skips execution when the room is null or the server is not GameServer or the client is disconnecting from GS already. OpLeaveRoom returns false in those cases and won't change the state, so check return of this method.

In some cases, this method will skip the OpLeave call and just call Disconnect(), which not only leaves the room but also the server. Disconnect also triggers a leave and so that workflow is is quicker.

Parameters
becomeInactiveIf true, this player becomes inactive in the game and can return later (if PlayerTTL of the room is != 0).
sendAuthCookieWebFlag: Securely transmit the encrypted object AuthCookie to the web service in PathLeave webhook when available
Returns
If the current room could be left (impossible while not in a room).
virtual bool OpRaiseEvent ( byte  eventCode,
object  customEventContent,
RaiseEventOptions  raiseEventOptions,
SendOptions  sendOptions 
)
virtual

Send an event with custom code/type and any content to the other players in the same room.

Parameters
eventCodeIdentifies this type of event (and the content). Your game's event codes can start with 0.
customEventContentAny serializable datatype (including Hashtable like the other OpRaiseEvent overloads).
raiseEventOptionsContains used send options. If you pass null, the default options will be used.
sendOptionsSend options for reliable, encryption etc
Returns
If operation could be enqueued for sending. Sent when calling: Service or SendOutgoingCommands.
bool OpRejoinRoom ( string  roomName)

Rejoins a room by roomName (using the userID internally to return). Will callback: OnJoinedRoom or OnJoinRoomFailed.

Used to return to a room, before this user was removed from the players list. Internally, the userID will be checked by the server, to make sure this user is in the room (active or inactice).

In contrast to join, this operation never adds a players to a room. It will attempt to retake an existing spot in the playerlist or fail. This makes sure the client doean't accidentally join a room when the game logic meant to re-activate an existing actor in an existing room.

This method will fail on the server, when the room does not exist, can't be loaded (persistent rooms) or when the userId is not in the player list of this room. This will lead to a callback OnJoinRoomFailed.

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.

bool OpSetCustomPropertiesOfActor ( int  actorNr,
Hashtable  propertiesToSet,
Hashtable  expectedProperties = null,
WebFlags  webFlags = null 
)

Updates and synchronizes a Player's Custom Properties. Optionally, expectedProperties can be provided as condition.

Custom Properties are a set of string keys and arbitrary values which is synchronized for the players in a Room. They are available when the client enters the room, as they are in the response of OpJoin and OpCreate.

Custom Properties either relate to the (current) Room or a Player (in that Room).

Both classes locally cache the current key/values and make them available as property: CustomProperties. This is provided only to read them. You must use the method SetCustomProperties to set/modify them.

Any client can set any Custom Properties anytime (when in a room). It's up to the game logic to organize how they are best used.

You should call SetCustomProperties only with key/values that are new or changed. This reduces traffic and performance.

Unless you define some expectedProperties, setting key/values is always permitted. In this case, the property-setting client will not receive the new values from the server but instead update its local cache in SetCustomProperties.

If you define expectedProperties, the server will skip updates if the server property-cache does not contain all expectedProperties with the same values. In this case, the property-setting client will get an update from the server and update it's cached key/values at about the same time as everyone else.

The benefit of using expectedProperties can be only one client successfully sets a key from one known value to another. As example: Store who owns an item in a Custom Property "ownedBy". It's 0 initally. When multiple players reach the item, they all attempt to change "ownedBy" from 0 to their actorNumber. If you use expectedProperties {"ownedBy", 0} as condition, the first player to take the item will have it (and the others fail to set the ownership).

Properties get saved with the game state for Turnbased games (which use IsPersistent = true).

Parameters
actorNrDefines which player the Custom Properties belong to. ActorID of a player.
propertiesToSetHashtable of Custom Properties that changes.
expectedPropertiesProvide some keys/values to use as condition for setting the new values. Client must be in room.
webFlagsDefines if the set properties should be forwarded to a WebHook. Client must be in room.
bool OpSetCustomPropertiesOfRoom ( Hashtable  propertiesToSet,
Hashtable  expectedProperties = null,
WebFlags  webFlags = null 
)

Updates and synchronizes this Room's Custom Properties. Optionally, expectedProperties can be provided as condition.

Custom Properties are a set of string keys and arbitrary values which is synchronized for the players in a Room. They are available when the client enters the room, as they are in the response of OpJoin and OpCreate.

Custom Properties either relate to the (current) Room or a Player (in that Room).

Both classes locally cache the current key/values and make them available as property: CustomProperties. This is provided only to read them. You must use the method SetCustomProperties to set/modify them.

Any client can set any Custom Properties anytime (when in a room). It's up to the game logic to organize how they are best used.

You should call SetCustomProperties only with key/values that are new or changed. This reduces traffic and performance.

Unless you define some expectedProperties, setting key/values is always permitted. In this case, the property-setting client will not receive the new values from the server but instead update its local cache in SetCustomProperties.

If you define expectedProperties, the server will skip updates if the server property-cache does not contain all expectedProperties with the same values. In this case, the property-setting client will get an update from the server and update it's cached key/values at about the same time as everyone else.

The benefit of using expectedProperties can be only one client successfully sets a key from one known value to another. As example: Store who owns an item in a Custom Property "ownedBy". It's 0 initally. When multiple players reach the item, they all attempt to change "ownedBy" from 0 to their actorNumber. If you use expectedProperties {"ownedBy", 0} as condition, the first player to take the item will have it (and the others fail to set the ownership).

Properties get saved with the game state for Turnbased games (which use IsPersistent = true).

Parameters
propertiesToSetHashtable of Custom Properties that changes.
expectedPropertiesProvide some keys/values to use as condition for setting the new values.
webFlagsDefines web flags for an optional PathProperties webhook.
bool OpSetPropertiesOfRoom ( Hashtable  gameProperties,
Hashtable  expectedProperties = null,
WebFlags  webFlags = null 
)

Internally used to cache and set properties (including well known properties).

Requires being in a room (because this attempts to send an operation which will fail otherwise).

bool OpWebRpc ( string  uriPath,
object  parameters,
bool  sendAuthCookie = false 
)

This operation makes Photon call your custom web-service by path/name with the given parameters (converted into Json).

A WebRPC calls a custom, http-based function on a server you provide. The uriPath is relative to a "base path" which is configured server-side. The sent parameters get converted from C# types to Json. Vice versa, the response of the web-service will be converted to C# types and sent back as normal operation response.

To use this feature, you have to setup your server:

For a Photon Cloud application, visit the Dashboard and setup "WebHooks". The BaseUrl is used for WebRPCs as well.

The response by Photon will call OnOperationResponse() with Code: OperationCode.WebRpc. To get this response, you can derive the LoadBalancingClient, or (much easier) you set a suitable OnOpResponseAction to be called.

It's important to understand that the OperationResponse tells you if the WebRPC could be called or not but the content of the response will contain the values the web-service sent (if any). If the web-service could not execute the request, it might return another error and a message. This is inside the OperationResponse.

The class WebRpcResponse is a helper-class that extracts the most valuable content from the WebRPC response.

To get a WebRPC response, set a OnOpResponseAction:

this.OnOpResponseAction = this.OpResponseHandler;

It could look like this:

public void OpResponseHandler(OperationResponse operationResponse)
{
    if (operationResponse.OperationCode == OperationCode.WebRpc)
    {
        if (operationResponse.ReturnCode != 0)
        {
            Console.WriteLine("WebRpc failed. Response: " + operationResponse.ToStringFull());
        }
        else
        {
            WebRpcResponse webResponse = new WebRpcResponse(operationResponse);
            Console.WriteLine(webResponse.DebugMessage);    // message from the webserver

            // do something with the response...
        }
    }
}
Parameters
uriPathThe url path to call, relative to the baseUrl configured on Photon's server-side.
parametersThe parameters to send to the web-service method.
sendAuthCookieDefines if the authentication cookie gets sent to a WebHook (if setup).
bool ReconnectAndRejoin ( )

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
False, if the conditions are not met. Then, this client does not attempt the ReconnectAndRejoin.
bool ReconnectToMaster ( )

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.

void RemoveCallbackTarget ( object  target)

Unregisters an object from callbacks for the implemented callback-interfaces.

The covered callback interfaces are: IConnectionCallbacks, IMatchmakingCallbacks, ILobbyCallbacks, IInRoomCallbacks, IOnEventCallback and IWebRpcCallback.

See: .Net Callbacks

Parameters
targetThe object that unregisters from getting callbacks.
void Service ( )

This method dispatches all available incoming commands and then sends this client's outgoing commands. It uses DispatchIncomingCommands and SendOutgoingCommands to do that.

The Photon client libraries are designed to fit easily into a game or application. The application is in control of the context (thread) in which incoming events and responses are executed and has full control of the creation of UDP/TCP packages.

Sending packages and dispatching received messages are two separate tasks. Service combines them into one method at the cost of control. It calls DispatchIncomingCommands and SendOutgoingCommands.

Call this method regularly (2..20 times a second).

This will Dispatch ANY received commands (unless a reliable command in-order is still missing) and events AND will send queued outgoing commands. Fewer calls might be more effective if a device cannot send many packets per second, as multiple operations might be combined into one package.

You could replace Service by:

while (DispatchIncomingCommands()); //Dispatch until everything is Dispatched...
SendOutgoingCommands(); //Send a UDP/TCP package with outgoing messages
See also
PhotonPeer.DispatchIncomingCommands, PhotonPeer.SendOutgoingCommands

Member Data Documentation

AuthModeOption AuthMode = AuthModeOption.Auth

Enables the new Authentication workflow.

Wraps up the target objects for a group of callbacks, so they can be called conveniently.

By using Add or Remove, objects can "subscribe" or "unsubscribe" for this group of callbacks.

bool EnableLobbyStatistics

If enabled, the client will get a list of available lobbies from the Master Server.

Set this value before the client connects to the Master Server. While connected to the Master Server, a change has no effect.

Implement OptionalInfoCallbacks.OnLobbyStatisticsUpdate, to get the list of used lobbies.

The lobby statistics can be useful if your title dynamically uses lobbies, depending (e.g.) on current player activity or such. In this case, getting a list of available lobbies, their room-count and player-count can be useful info.

ConnectUsingSettings sets this to the PhotonServerSettings value.

EncryptionMode EncryptionMode = EncryptionMode.PayloadEncryption

Defines how the communication gets encrypted.

ConnectionProtocol ExpectedProtocol = ConnectionProtocol.Udp

The protocol which will be used on Master- and Gameserver.

When using AuthMode = AuthModeOption.AuthOnceWss, the client uses a wss-connection on the Nameserver but another protocol on the other servers. As the Nameserver sends an address, which is different per protocol, it needs to know the expected protocol.

summary>Simplifies getting the token for connect/init requests, if this feature is enabled.

Wraps up the target objects for a group of callbacks, so they can be called conveniently.

By using Add or Remove, objects can "subscribe" or "unsubscribe" for this group of callbacks.

string NameServerHost = "ns.exitgames.com"

Name Server Host Name for Photon Cloud. Without port and without any prefix.

string NameServerHttp = "http://ns.exitgames.com:80/photon/n"

Name Server for HTTP connections to the Photon Cloud. Includes prefix and port.

Contains the list if enabled regions this client may use. Null, unless the client got a response to OpGetRegions.

Property Documentation

string AppId
getset

The AppID as assigned from the Photon Cloud. If you host yourself, this is the "regular" Photon Server Application Name (most likely: "LoadBalancing").

string AppVersion
getset

The version of your client. A new version also creates a new "virtual app" to separate players from older client versions.

AuthenticationValues AuthValues
getset

User authentication values to be sent to the Photon server right after connecting.

Set this property or pass AuthenticationValues by Connect(..., authValues).

string CloudRegion
getset

The cloud region this client connects to. Set by ConnectToRegionMaster(). Not set if you don't use a NameServer!

TypedLobby CurrentLobby
getset

The lobby this client currently uses. Defined when joining a lobby or creating rooms

Room CurrentRoom
getset

The current room this client is connected to (null if none available).

string CurrentServerAddress
get

The currently used server address (if any). The type of server is define by Server property.

DisconnectCause DisconnectedCause
getset

Summarizes (aggregates) the different causes for disconnects of a client.

A disconnect can be caused by: errors in the network connection or some vital operation failing (which is considered "high level"). While operations always trigger a call to OnOperationResponse, connection related changes are treated in OnStatusChanged. The DisconnectCause is set in either case and summarizes the causes for any disconnect in a single state value which can be used to display (or debug) the cause for disconnection.

string GameServerAddress
getset

The game server's address for a particular room. In use temporarily, as assigned by master.

bool InLobby
getset

Internal value if the client is in a lobby.

This is used to re-set this.State, when joining/creating a room fails.

bool InRoom
get

Is true while being in a room (this.state == ClientState.Joined).

Aside from polling this value, game logic should implement IMatchmakingCallbacks in some class and react when that gets called.
OpRaiseEvent, OpLeave and some other operations can only be used (successfully) when the client is in a room. PUN's PhotonNetwork.InRoom will support being InRoom in it's offline mode (by providing it's own property).

bool IsConnected
get

Returns if this client is currently connected or connecting to some type of server.

This is even true while switching servers. Use IsConnectedAndReady to check only for those states that enable you to send Operations.

bool IsConnectedAndReady
get

A refined version of IsConnected which is true only if your connection is ready to send operations.

Not all operations can be called on all types of servers. If an operation is unavailable on the currently connected server, this will result in a OperationResponse with ErrorCode != 0.

Examples: The NameServer allows OpGetRegions which is not available anywhere else. The MasterServer does not allow you to send events (OpRaiseEvent) and on the GameServer you are unable to join a lobby (OpJoinLobby).

To check which server you are on, use: PhotonNetwork.Server.

bool IsFetchingFriendList
get

Internal flag to know if the client currently fetches a friend list.

bool IsUsingNameServer
getset

True if this client uses a NameServer to get the Master Server address.

This value is public, despite being an internal value, which should only be set by this client or PUN.

The client uses a LoadBalancingPeer as API to communicate with the server. This is public for ease-of-use: Some methods like OpRaiseEvent are not relevant for the connection state and don't need a override.

Player LocalPlayer
getset

The local player is never null but not valid unless the client is in a room, too. The ID will be -1 outside of rooms.

string MasterServerAddress
getset

Your Master Server address. In PhotonCloud, call ConnectToRegionMaster() to find your Master Server.

In the Photon Cloud, explicit definition of a Master Server Address is not best practice. The Photon Cloud has a "Name Server" which redirects clients to a specific Master Server (per Region and AppId).

string NameServerAddress
get

Name Server Address for Photon Cloud (based on current protocol). You can use the default values and usually won't have to set this value.

string NickName
getset

The nickname of the player (synced with others). Same as client.LocalPlayer.NickName.

int PlayersInRoomsCount
getset

Statistic value available on master server: Players in rooms (playing).

int PlayersOnMasterCount
getset

Statistic value available on master server: Players on master (looking for games).

int RoomsCount
getset

Statistic value available on master server: Rooms currently created.

ServerConnection Server
getset

The server this client is currently connected or connecting to.

Each server (NameServer, MasterServer, GameServer) allow some operations and reject others.

ClientState State
getset

Current state this client is in. Careful: several states are "transitions" that lead to other states.

bool UseAlternativeUdpPorts
getset

Use the alternative ports for UDP connections in the Public Cloud (27000 to 27003).

This should be used when players have issues with connection stability. Some players reported better connectivity for Steam games. The effect might vary, which is why the alternative ports are not the new default.

The alternative (server) ports are 27000 up to 27003.

The values are appplied by replacing any incoming server-address string accordingly. You only need to set this to true though.

This value does not affect TCP or WebSocket connections.

string UserId
getset

An ID for this user. Sent in OpAuthenticate when you connect. If not set, the PlayerName is applied during connect.

On connect, if the UserId is null or empty, the client will copy the PlayName to UserId. If PlayerName is not set either (before connect), the server applies a temporary ID which stays unknown to this client and other clients.

The UserId is what's used in FindFriends and for fetching data for your account (with WebHooks e.g.).

By convention, set this ID before you connect, not while being connected. There is no error but the ID won't change while being connected.

Event Documentation

Action<EventData> EventReceived

Register a method to be called when an event got dispatched. Gets called after the LoadBalancingClient handled the internal events first.

This is an alternative to extending LoadBalancingClient to override OnEvent().

Note that OnEvent is calling EventReceived after it handled internal events first. That means for example: Joining players will already be in the player list but leaving players will already be removed from the room.

Action<OperationResponse> OpResponseReceived

Register a method to be called when an operation response is received.

This is an alternative to extending LoadBalancingClient to override OnOperationResponse().

Note that OnOperationResponse gets executed before your Action is called. That means for example: The OpJoinLobby response already set the state to "JoinedLobby" and the response to OpLeave already triggered the Disconnect before this is called.

Action<ClientState, ClientState> StateChanged

Register a method to be called when this client's ClientState gets set.

This can be useful to react to being connected, joined into a room, etc.