Photon Unity Networking 2 2.22

Public Member Functions | Public Attributes | Static Public Attributes | Properties | List of all members
ChatClient Class Reference

Central class of the Photon Chat API to connect, handle channels and messages. More...

Inherits IPhotonPeerListener.

Public Member Functions

bool CanChatInChannel (string channelName)
 Checks if this client is ready to publish messages inside a public channel. More...
 
 ChatClient (IChatClientListener listener, ConnectionProtocol protocol=ConnectionProtocol.Udp)
 Chat client constructor. More...
 
bool ConnectUsingSettings (ChatAppSettings appSettings)
 
bool Connect (string appId, string appVersion, AuthenticationValues authValues)
 Connects this client to the Photon Chat Cloud service, which will also authenticate the user (and set a UserId). More...
 
bool ConnectAndSetStatus (string appId, string appVersion, AuthenticationValues authValues, int status=ChatUserStatus.Online, object message=null)
 Connects this client to the Photon Chat Cloud service, which will also authenticate the user (and set a UserId). This also sets an online status once connected. By default it will set user status to ChatUserStatus.Online. See SetOnlineStatus(int,object) for more information. More...
 
void Service ()
 Must be called regularly to keep connection between client and server alive and to process incoming messages. More...
 
void SendAcksOnly ()
 Obsolete: Better use UseBackgroundWorkerForSending and Service(). More...
 
void Disconnect (ChatDisconnectCause cause=ChatDisconnectCause.DisconnectByClientLogic)
 Disconnects from the Chat Server by sending a "disconnect command", which prevents a timeout server-side. More...
 
void StopThread ()
 Locally shuts down the connection to the Chat Server. This resets states locally but the server will have to timeout this peer. More...
 
bool Subscribe (string[] channels)
 Sends operation to subscribe to a list of channels by name. More...
 
bool Subscribe (string[] channels, int[] lastMsgIds)
 Sends operation to subscribe to a list of channels by name and possibly retrieve messages we did not receive while unsubscribed. More...
 
bool Subscribe (string[] channels, int messagesFromHistory)
 Sends operation to subscribe client to channels, optionally fetching a number of messages from the cache. More...
 
bool Unsubscribe (string[] channels)
 Unsubscribes from a list of channels, which stops getting messages from those. More...
 
bool PublishMessage (string channelName, object message, bool forwardAsWebhook=false)
 Sends a message to a public channel which this client subscribed to. More...
 
bool SendPrivateMessage (string target, object message, bool forwardAsWebhook=false)
 Sends a private message to a single target user. Calls OnPrivateMessage on the receiving client. More...
 
bool SendPrivateMessage (string target, object message, bool encrypt, bool forwardAsWebhook)
 Sends a private message to a single target user. Calls OnPrivateMessage on the receiving client. More...
 
bool SetOnlineStatus (int status)
 Sets the user's status without changing your status-message. More...
 
bool SetOnlineStatus (int status, object message)
 Sets the user's status without changing your status-message. More...
 
bool AddFriends (string[] friends)
 Adds friends to a list on the Chat Server which will send you status updates for those. More...
 
bool RemoveFriends (string[] friends)
 Removes the provided entries from the list on the Chat Server and stops their status updates. More...
 
string GetPrivateChannelNameByUser (string userName)
 Get you the (locally used) channel name for the chat between this client and another user. More...
 
bool TryGetChannel (string channelName, bool isPrivate, out ChatChannel channel)
 Simplified access to either private or public channels by name. More...
 
bool TryGetChannel (string channelName, out ChatChannel channel)
 Simplified access to all channels by name. Checks public channels first, then private ones. More...
 
bool TryGetPrivateChannelByUser (string userId, out ChatChannel channel)
 Simplified access to private channels by target user. More...
 
bool Subscribe (string channel, int lastMsgId=0, int messagesFromHistory=-1, ChannelCreationOptions creationOptions=null)
 Subscribe to a single channel and optionally sets its well-know channel properties in case the channel is created. More...
 

Public Attributes

int MessageLimit
 If greater than 0, new channels will limit the number of messages they cache locally. More...
 
readonly Dictionary< string, ChatChannelPublicChannels
 Public channels this client is subscribed to. More...
 
readonly Dictionary< string, ChatChannelPrivateChannels
 Private channels in which this client has exchanged messages. More...
 
ChatPeer chatPeer = null
 The Chat Peer used by this client. More...
 

Static Public Attributes

const int DefaultMaxSubscribers = 100
 Default maximum value possible for ChatChannel.MaxSubscribers when ChatChannel.PublishSubscribers is enabled More...
 

Properties

string NameServerAddress [get]
 The address of last connected Name Server. More...
 
string FrontendAddress [get]
 The address of the actual chat server assigned from NameServer. Public for read only. More...
 
string ChatRegion [get, set]
 Settable only before you connect! Defaults to "EU". More...
 
ChatState State [get]
 Current state of the ChatClient. Also use CanChat. More...
 
ChatDisconnectCause DisconnectedCause [get]
 Disconnection cause. Check this inside IChatClientListener.OnDisconnected. More...
 
bool CanChat [get]
 Checks if this client is ready to send messages. More...
 
string AppVersion [get]
 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]
 The AppID as assigned from the Photon Cloud. More...
 
AuthenticationValues AuthValues [get, set]
 Settable only before you connect! More...
 
string? UserId [get]
 The unique ID of a user/person, stored in AuthValues.UserId. Set it before you connect. More...
 
bool UseBackgroundWorkerForSending [get, set]
 Defines if a background thread will call SendOutgoingCommands, while your code calls Service to dispatch received messages. More...
 
ConnectionProtocol? TransportProtocol [get, set]
 Exposes the TransportProtocol of the used PhotonPeer. Settable while not connected. More...
 
Dictionary< ConnectionProtocol, Type > SocketImplementationConfig [get]
 Defines which IPhotonSocket class to use per ConnectionProtocol. More...
 
DebugLevel DebugOut [get, set]
 Sets the level (and amount) of debug output provided by the library. More...
 

Detailed Description

Central class of the Photon Chat API to connect, handle channels and messages.

This class must be instantiated with a IChatClientListener instance to get the callbacks. Integrate it into your game loop by calling Service regularly. If the target platform supports Threads/Tasks, set UseBackgroundWorkerForSending = true, to let the ChatClient keep the connection by sending from an independent thread.

Call Connect with an AppId that is setup as Photon Chat application. Note: Connect covers multiple messages between this client and the servers. A short workflow will connect you to a chat server.

Each ChatClient resembles a user in chat (set in Connect). Each user automatically subscribes a channel for incoming private messages and can message any other user privately. Before you publish messages in any non-private channel, that channel must be subscribed.

PublicChannels is a list of subscribed channels, containing messages and senders. PrivateChannels contains all incoming and sent private messages.

Constructor & Destructor Documentation

◆ ChatClient()

ChatClient ( IChatClientListener  listener,
ConnectionProtocol  protocol = ConnectionProtocol.Udp 
)

Chat client constructor.

Parameters
listenerThe chat listener implementation.
protocolConnection protocol to be used by this client. Default is ConnectionProtocol.Udp.

Member Function Documentation

◆ AddFriends()

bool AddFriends ( string[]  friends)

Adds friends to a list on the Chat Server which will send you status updates for those.

AddFriends and RemoveFriends enable clients to handle their friend list in the Photon Chat server. Having users on your friends list gives you access to their current online status (and whatever info your client sets in it).

Each user can set an online status consisting of an integer and an arbitrary (serializable) object. The object can be null, Hashtable, object[] or anything else Photon can serialize.

The status is published automatically to friends (anyone who set your user ID with AddFriends).

Photon flushes friends-list when a chat client disconnects, so it has to be set each time. If your community API gives you access to online status already, you could filter and set online friends in AddFriends.

Actual friend relations are not persistent and have to be stored outside of Photon.

Parameters
friendsArray of friend userIds.
Returns
If the operation could be sent.

◆ CanChatInChannel()

bool CanChatInChannel ( string  channelName)

Checks if this client is ready to publish messages inside a public channel.

Parameters
channelNameThe channel to do the check with.
Returns
Whether or not this client is ready to publish messages inside the public channel with the specified channelName.

◆ Connect()

bool Connect ( string  appId,
string  appVersion,
AuthenticationValues  authValues 
)

Connects this client to the Photon Chat Cloud service, which will also authenticate the user (and set a UserId).

Parameters
appIdGet your Photon Chat AppId from the Dashboard.
appVersionAny version string you make up. Used to separate users and variants of your clients, which might be incompatible.
authValuesValues for authentication. You can leave this null, if you set a UserId before. If you set authValues, they will override any UserId set before.
Returns

◆ ConnectAndSetStatus()

bool ConnectAndSetStatus ( string  appId,
string  appVersion,
AuthenticationValues  authValues,
int  status = ChatUserStatus.Online,
object  message = null 
)

Connects this client to the Photon Chat Cloud service, which will also authenticate the user (and set a UserId). This also sets an online status once connected. By default it will set user status to ChatUserStatus.Online. See SetOnlineStatus(int,object) for more information.

Parameters
appIdGet your Photon Chat AppId from the Dashboard.
appVersionAny version string you make up. Used to separate users and variants of your clients, which might be incompatible.
authValuesValues for authentication. You can leave this null, if you set a UserId before. If you set authValues, they will override any UserId set before.
statusUser status to set when connected. Predefined states are in class ChatUserStatus. Other values can be used at will.
messageOptional status Also sets a status-message which your friends can get.
Returns
If the connection attempt could be sent at all.

◆ Disconnect()

Disconnects from the Chat Server by sending a "disconnect command", which prevents a timeout server-side.

◆ GetPrivateChannelNameByUser()

string GetPrivateChannelNameByUser ( string  userName)

Get you the (locally used) channel name for the chat between this client and another user.

Parameters
userNameRemote user's name or UserId.
Returns
The (locally used) channel name for a private channel.

Do not subscribe to this channel. Private channels do not need to be explicitly subscribed to. Use this for debugging purposes mainly.

◆ PublishMessage()

bool PublishMessage ( string  channelName,
object  message,
bool  forwardAsWebhook = false 
)

Sends a message to a public channel which this client subscribed to.

Before you publish to a channel, you have to subscribe it. Everyone in that channel will get the message.

Parameters
channelNameName of the channel to publish to.
messageYour message (string or any serializable data).
forwardAsWebhookOptionally, public messages can be forwarded as webhooks. Configure webhooks for your Chat app to use this.
Returns
False if the client is not yet ready to send messages.

◆ RemoveFriends()

bool RemoveFriends ( string[]  friends)

Removes the provided entries from the list on the Chat Server and stops their status updates.

Photon flushes friends-list when a chat client disconnects. Unless you want to remove individual entries, you don't have to RemoveFriends.

AddFriends and RemoveFriends enable clients to handle their friend list in the Photon Chat server. Having users on your friends list gives you access to their current online status (and whatever info your client sets in it).

Each user can set an online status consisting of an integer and an arbitratry (serializable) object. The object can be null, Hashtable, object[] or anything else Photon can serialize.

The status is published automatically to friends (anyone who set your user ID with AddFriends).

Photon flushes friends-list when a chat client disconnects, so it has to be set each time. If your community API gives you access to online status already, you could filter and set online friends in AddFriends.

Actual friend relations are not persistent and have to be stored outside of Photon.

AddFriends and RemoveFriends enable clients to handle their friend list in the Photon Chat server. Having users on your friends list gives you access to their current online status (and whatever info your client sets in it).

Each user can set an online status consisting of an integer and an arbitratry (serializable) object. The object can be null, Hashtable, object[] or anything else Photon can serialize.

The status is published automatically to friends (anyone who set your user ID with AddFriends).

Actual friend relations are not persistent and have to be stored outside of Photon.

Parameters
friendsArray of friend userIds.
Returns
If the operation could be sent.

◆ SendAcksOnly()

void SendAcksOnly ( )

Obsolete: Better use UseBackgroundWorkerForSending and Service().

◆ SendPrivateMessage() [1/2]

bool SendPrivateMessage ( string  target,
object  message,
bool  encrypt,
bool  forwardAsWebhook 
)

Sends a private message to a single target user. Calls OnPrivateMessage on the receiving client.

Parameters
targetUsername to send this message to.
messageThe message you want to send. Can be a simple string or anything serializable.
encryptOptionally, private messages can be encrypted. Encryption is not end-to-end as the server decrypts the message.
forwardAsWebhookOptionally, private messages can be forwarded as webhooks. Configure webhooks for your Chat app to use this.
Returns
True if this clients can send the message to the server.

◆ SendPrivateMessage() [2/2]

bool SendPrivateMessage ( string  target,
object  message,
bool  forwardAsWebhook = false 
)

Sends a private message to a single target user. Calls OnPrivateMessage on the receiving client.

Parameters
targetUsername to send this message to.
messageThe message you want to send. Can be a simple string or anything serializable.
forwardAsWebhookOptionally, private messages can be forwarded as webhooks. Configure webhooks for your Chat app to use this.
Returns
True if this clients can send the message to the server.

◆ Service()

void Service ( )

Must be called regularly to keep connection between client and server alive and to process incoming messages.

This method limits the effort it does automatically using the private variable msDeltaForServiceCalls. That value is lower for connect and multiplied by 4 when chat-server connection is ready.

◆ SetOnlineStatus() [1/2]

bool SetOnlineStatus ( int  status)

Sets the user's status without changing your status-message.

The predefined status values can be found in class ChatUserStatus. State ChatUserStatus.Invisible will make you offline for everyone and send no message.

You can set custom values in the status integer. Aside from the pre-configured ones, all states will be considered visible and online. Else, no one would see the custom state.

This overload does not change the set message.

Parameters
statusPredefined states are in class ChatUserStatus. Other values can be used at will.
Returns
True if the operation gets called on the server.

◆ SetOnlineStatus() [2/2]

bool SetOnlineStatus ( int  status,
object  message 
)

Sets the user's status without changing your status-message.

The predefined status values can be found in class ChatUserStatus. State ChatUserStatus.Invisible will make you offline for everyone and send no message.

You can set custom values in the status integer. Aside from the pre-configured ones, all states will be considered visible and online. Else, no one would see the custom state.

The message object can be anything that Photon can serialize, including (but not limited to) Hashtable, object[] and string. This value is defined by your own conventions.

Parameters
statusPredefined states are in class ChatUserStatus. Other values can be used at will.
messageAlso sets a status-message which your friends can get.
Returns
True if the operation gets called on the server.

◆ StopThread()

void StopThread ( )

Locally shuts down the connection to the Chat Server. This resets states locally but the server will have to timeout this peer.

◆ Subscribe() [1/4]

bool Subscribe ( string  channel,
int  lastMsgId = 0,
int  messagesFromHistory = -1,
ChannelCreationOptions  creationOptions = null 
)

Subscribe to a single channel and optionally sets its well-know channel properties in case the channel is created.

Parameters
channelname of the channel to subscribe to
lastMsgIdID of the last received message from this channel when re subscribing to receive only missed messages, default is 0
messagesFromHistoryhow many missed messages to receive from history, default is none/-1
creationOptionsoptions to be used in case the channel to subscribe to will be created.
Returns

◆ Subscribe() [2/4]

bool Subscribe ( string[]  channels)

Sends operation to subscribe to a list of channels by name.

Parameters
channelsList of channels to subscribe to. Avoid null or empty values.
Returns
If the operation could be sent at all (Example: Fails if not connected to Chat Server).

◆ Subscribe() [3/4]

bool Subscribe ( string[]  channels,
int  messagesFromHistory 
)

Sends operation to subscribe client to channels, optionally fetching a number of messages from the cache.

Subscribes channels will forward new messages to this user. Use PublishMessage to do so. The messages cache is limited but can be useful to get into ongoing conversations, if that's needed.

Parameters
channelsList of channels to subscribe to. Avoid null or empty values.
messagesFromHistory0: no history. 1 and higher: number of messages in history. -1: all available history.
Returns
If the operation could be sent at all (Example: Fails if not connected to Chat Server).

◆ Subscribe() [4/4]

bool Subscribe ( string[]  channels,
int[]  lastMsgIds 
)

Sends operation to subscribe to a list of channels by name and possibly retrieve messages we did not receive while unsubscribed.

Parameters
channelsList of channels to subscribe to. Avoid null or empty values.
lastMsgIdsID of last message received per channel. Useful when re subscribing to receive only messages we missed.
Returns
If the operation could be sent at all (Example: Fails if not connected to Chat Server).

◆ TryGetChannel() [1/2]

bool TryGetChannel ( string  channelName,
bool  isPrivate,
out ChatChannel  channel 
)

Simplified access to either private or public channels by name.

Parameters
channelNameName of the channel to get. For private channels, the channel-name is composed of both user's names.
isPrivateDefine if you expect a private or public channel.
channelOut parameter gives you the found channel, if any.
Returns
True if the channel was found.

Public channels exist only when subscribed to them. Private channels exist only when at least one message is exchanged with the target user privately.

◆ TryGetChannel() [2/2]

bool TryGetChannel ( string  channelName,
out ChatChannel  channel 
)

Simplified access to all channels by name. Checks public channels first, then private ones.

Parameters
channelNameName of the channel to get.
channelOut parameter gives you the found channel, if any.
Returns
True if the channel was found.

Public channels exist only when subscribed to them. Private channels exist only when at least one message is exchanged with the target user privately.

◆ TryGetPrivateChannelByUser()

bool TryGetPrivateChannelByUser ( string  userId,
out ChatChannel  channel 
)

Simplified access to private channels by target user.

Parameters
userIdUserId of the target user in the private channel.
channelOut parameter gives you the found channel, if any.
Returns
True if the channel was found.

◆ Unsubscribe()

bool Unsubscribe ( string[]  channels)

Unsubscribes from a list of channels, which stops getting messages from those.

The client will remove these channels from the PublicChannels dictionary once the server sent a response to this request.

The request will be sent to the server and IChatClientListener.OnUnsubscribed gets called when the server actually removed the channel subscriptions.

Unsubscribe will fail if you include null or empty channel names.

Parameters
channelsNames of channels to unsubscribe.
Returns
False, if not connected to a chat server.

Member Data Documentation

◆ chatPeer

ChatPeer chatPeer = null

The Chat Peer used by this client.

◆ DefaultMaxSubscribers

const int DefaultMaxSubscribers = 100
static

Default maximum value possible for ChatChannel.MaxSubscribers when ChatChannel.PublishSubscribers is enabled

◆ MessageLimit

int MessageLimit

If greater than 0, new channels will limit the number of messages they cache locally.

This can be useful to limit the amount of memory used by chats. You can set a MessageLimit per channel but this value gets applied to new ones.

Note: Changing this value, does not affect ChatChannels that are already in use!

◆ PrivateChannels

readonly Dictionary<string, ChatChannel> PrivateChannels

Private channels in which this client has exchanged messages.

◆ PublicChannels

readonly Dictionary<string, ChatChannel> PublicChannels

Public channels this client is subscribed to.

Property Documentation

◆ AppId

string AppId
get

The AppID as assigned from the Photon Cloud.

◆ AppVersion

string AppVersion
get

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

◆ AuthValues

AuthenticationValues AuthValues
getset

Settable only before you connect!

◆ CanChat

bool CanChat
get

Checks if this client is ready to send messages.

◆ ChatRegion

string ChatRegion
getset

Settable only before you connect! Defaults to "EU".

◆ DebugOut

DebugLevel DebugOut
getset

Sets the level (and amount) of debug output provided by the library.

This affects the callbacks to IChatClientListener.DebugReturn. Default Level: Error.

◆ DisconnectedCause

ChatDisconnectCause DisconnectedCause
get

Disconnection cause. Check this inside IChatClientListener.OnDisconnected.

◆ FrontendAddress

string FrontendAddress
get

The address of the actual chat server assigned from NameServer. Public for read only.

◆ NameServerAddress

string NameServerAddress
get

The address of last connected Name Server.

◆ SocketImplementationConfig

Dictionary<ConnectionProtocol, Type> SocketImplementationConfig
get

Defines which IPhotonSocket class to use per ConnectionProtocol.

Several platforms have special Socket implementations and slightly different APIs. To accomodate this, switching the socket implementation for a network protocol was made available. By default, UDP and TCP have socket implementations assigned.

You only need to set the SocketImplementationConfig once, after creating a PhotonPeer and before connecting. If you switch the TransportProtocol, the correct implementation is being used.

◆ State

ChatState State
get

Current state of the ChatClient. Also use CanChat.

◆ TransportProtocol

ConnectionProtocol? TransportProtocol
getset

Exposes the TransportProtocol of the used PhotonPeer. Settable while not connected.

◆ UseBackgroundWorkerForSending

bool UseBackgroundWorkerForSending
getset

Defines if a background thread will call SendOutgoingCommands, while your code calls Service to dispatch received messages.

The benefit of using a background thread to call SendOutgoingCommands is this:

Even if your game logic is being paused, the background thread will keep the connection to the server up. On a lower level, acknowledgements and pings will prevent a server-side timeout while (e.g.) Unity loads assets.

Your game logic still has to call Service regularly, or else incoming messages are not dispatched. As this typically triggers UI updates, it's easier to call Service from the main/UI thread.

◆ UserId

string? UserId
get

The unique ID of a user/person, stored in AuthValues.UserId. Set it before you connect.

This value wraps AuthValues.UserId. It's not a nickname and we assume users with the same userID are the same person.