Photon3Unity3D
This is a substitute for the Hashtable class, missing in: Win8RT and Windows Phone. It uses a Dictionary<object,object> as base.
Please be aware that this class might act differently than the Hashtable equivalent.
As far as Photon is concerned, the substitution is sufficiently precise.
Creates a shallow copy of the Hashtable.
A shallow copy of a collection copies only the elements of the collection, whether they are
reference types or value types, but it does not copy the objects that the references refer
to. The references in the new collection point to the same objects that the references in
the original collection point to.
Shallow copy of the Hashtable.
Contains several (more or less) useful static methods, mostly used for debugging.
Gets the local machine's "milliseconds since start" value (precision is described in remarks).
This method uses Environment.TickCount (cheap but with only 16ms precision).
PhotonPeer.LocalMsTimestampDelegate is available to set the delegate (unless already connected).
Fraction of the current time in Milliseconds (this is not a proper datetime timestamp).
Creates a background thread that calls the passed function in 100ms intervals, as long as that returns true.
Creates a background thread that calls the passed function in 100ms intervals, as long as that returns true.
Milliseconds to sleep between calls of myThread.
Writes the exception's stack trace to the received stream.
Exception to obtain information from.
Output sream used to write to.
Writes the exception's stack trace to the received stream. Writes to: System.Diagnostics.Debug.
Exception to obtain information from.
This method returns a string, representing the content of the given IDictionary.
Returns "null" if parameter is null.
IDictionary to return as string.
The string representation of keys and values in IDictionary.
This method returns a string, representing the content of the given IDictionary.
Returns "null" if parameter is null.
IDictionary to return as string.
Converts a byte-array to string (useful as debugging output).
Uses BitConverter.ToString(list) internally after a null-check of list.
Byte-array to convert to string.
List of bytes as string.
Class to wrap static access to the random.Next() call in a thread safe manner.
Defines block size for encryption/decryption algorithm
Defines IV size for encryption/decryption algorithm
Defines HMAC size for packet authentication algorithm
Enumeration of situations that change the peers internal status.
Used in calls to OnStatusChanged to inform your application of various situations that might happen.
Most of these codes are referenced somewhere else in the documentation when they are relevant to methods.
the PhotonPeer is connected.
See {@link PhotonListener#OnStatusChanged}*
the PhotonPeer just disconnected.
See {@link PhotonListener#OnStatusChanged}*
the PhotonPeer encountered an exception and will disconnect, too.
See {@link PhotonListener#OnStatusChanged}*
the PhotonPeer encountered an exception while opening the incoming connection to the server. The server could be down / not running or the client has no network or a misconfigured DNS.
See {@link PhotonListener#OnStatusChanged}*
Used on platforms that throw a security exception on connect. Unity3d does this, e.g., if a webplayer build could not fetch a policy-file from a remote server.
PhotonPeer outgoing queue is filling up. send more often.
PhotonPeer outgoing queue is filling up. send more often.
Sending command failed. Either not connected, or the requested channel is bigger than the number of initialized channels.
PhotonPeer outgoing queue is filling up. send more often.
PhotonPeer incoming queue is filling up. Dispatch more often.
PhotonPeer incoming queue is filling up. Dispatch more often.
PhotonPeer incoming queue is filling up. Dispatch more often.
Exception, if a server cannot be connected. Most likely, the server is not responding. Ask user to try again later.
Exception, if a server cannot be connected. Most likely, the server is not responding. Ask user to try again later.
Disconnection due to a timeout (client did no longer receive ACKs from server).
Disconnect by server due to timeout (received a disconnect command, cause server misses ACKs of client).
Disconnect by server due to concurrent user limit reached (received a disconnect command).
Disconnect by server due to server's logic (received a disconnect command).
Tcp Router Response. Only used when Photon is setup as TCP router! Routing is ok.
Tcp Router Response. Only used when Photon is setup as TCP router! Routing node unknown. Check client connect values.
Tcp Router Response. Only used when Photon is setup as TCP router! Routing endpoint unknown.
Tcp Router Response. Only used when Photon is setup as TCP router! Routing not setup yet. Connect again.
(1048) Value for OnStatusChanged()-call, when the encryption-setup for secure communication finished successfully.
(1049) Value for OnStatusChanged()-call, when the encryption-setup failed for some reason. Check debug logs.
Callback interface for the Photon client side. Must be provided to a new PhotonPeer in its constructor.
These methods are used by your PhotonPeer instance to keep your app updated. Read each method's
description and check out the samples to see how to use them.
Provides textual descriptions for various error conditions and noteworthy situations.
In cases where the application needs to react, a call to OnStatusChanged is used.
OnStatusChanged gives "feedback" to the game, DebugReturn provies human readable messages
on the background.
All debug output of the library will be reported through this method. Print it or put it in a
buffer to use it on-screen. Use PhotonPeer.DebugOut to select how verbose the output is.
DebugLevel (severity) of the message.
Debug text. Print to System.Console or screen.
Callback method which gives you (async) responses for called operations.
Similar to method-calling, operations can have a result.
Because operation-calls are non-blocking and executed on the server, responses are provided
after a roundtrip as call to this method.
Example: Trying to create a room usually succeeds but can fail if the room's name is already
in use (room names are their IDs).
This method is used as general callback for all operations. Each response corresponds to a certain
"type" of operation by its OperationCode.
When you join a room, the server will assign a consecutive number to each client: the
"actorNr" or "player number". This is sent back in the OperationResult's
Parameters as value of key .
Fetch your actorNr of a Join response like this:
int actorNr = (int)operationResponse[(byte)OperationCode.ActorNr];
The response to an operation\-call.
OnStatusChanged is called to let the game know when asyncronous actions finished or when errors happen.
Not all of the many StatusCode values will apply to your game. Example: If you don't use encryption,
the respective status changes are never made.
The values are all part of the StatusCode enumeration and described value-by-value.
A code to identify the situation.
Called whenever an event from the Photon Server is dispatched.
Events are used for communication between clients and allow the server to update clients over time.
The creation of an event is often triggered by an operation (called by this client or an other).
Each event carries its specific content in its Parameters. Your application knows which content to
expect by checking the event's 'type', given by the event's Code.
Events can be defined and extended server-side.
If you use the LoadBalancing application as base, several events like EvJoin and EvLeave are already defined.
For these events and their Parameters, the library provides constants, so check the EventCode and ParameterCode
classes.
Photon also allows you to come up with custom events on the fly, purely client-side. To do so, use
OpRaiseEvent.
Events are buffered on the client side and must be Dispatched. This way, OnEvent is always taking
place in the same thread as a call.
The event currently being dispatched.
Value range for a Peer's connection and initialization state, as returned by the PeerState property.
While this is not the same as the StatusCode of IPhotonPeerListener.OnStatusChanged(), it directly relates to it.
In most cases, it makes more sense to build a game's state on top of the OnStatusChanged() as you get changes.
The peer is disconnected and can't call Operations. Call Connect().
The peer is establishing the connection: opening a socket, exchanging packages with Photon.
The connection is established and now sends the application name to Photon.
You set the "application name" by calling PhotonPeer.Connect().
The peer is connected and initialized (selected an application). You can now use operations.
The peer is disconnecting. It sent a disconnect to the server, which will acknowledge closing the connection.
These are the options that can be used as underlying transport protocol.
Use UDP to connect to Photon, which allows you to send operations reliable or unreliable on demand.
Use TCP to connect to Photon.
A TCP-based protocol commonly supported by browsers.For WebGL games mostly. Note: No WebSocket IPhotonSocket implementation is in this Assembly.
This protocol is only available in Unity exports to WebGL.
A TCP-based, encrypted protocol commonly supported by browsers. For WebGL games mostly. Note: No WebSocket IPhotonSocket implementation is in this Assembly.
This protocol is only available in Unity exports to WebGL.
Level / amount of DebugReturn callbacks. Each debug level includes output for lower ones: OFF, ERROR, WARNING, INFO, ALL.
No debug out.
Only error descriptions.
Warnings and errors.
Information about internal workflows, warnings and errors.
Most complete workflow description (but lots of debug output), info, warnings and errors.
Instances of the PhotonPeer class are used to connect to a Photon server and communicate with it.
A PhotonPeer instance allows communication with the Photon Server, which in turn distributes messages
to other PhotonPeer clients.
An application can use more than one PhotonPeer instance, which are treated as separate users on the
server. Each should have its own listener instance, to separate the operations, callbacks and events.
False if this library build contains C# Socket code. If true, you must set some type as SocketImplementation before connecting.
True, if this library needs a native Photon "Encryptor" plugin library for "Datagram Encryption". If false, this dll attempts to use managed encryption.
True if the library was compiled with DEBUG setting.
A simplified identifier for client SDKs. Photon's APIs might modify this (as a dll can be used in more than one product). Helps debugging.
For the Init-request, we shift the ClientId by one and the last bit signals a "debug" (0) or "release" build (1).
Defines if Key Exchange for Encryption is done asynchronously in another thread.
Version of this library as string.
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.
Can be used to read the IPhotonSocket implementation at runtime (before connecting).
Use the SocketImplementationConfig to define which IPhotonSocket is used per ConnectionProtocol.
Sets the level (and amount) of debug output provided by the library.
This affects the callbacks to IPhotonPeerListener.DebugReturn.
Default Level: Error.
Gets the IPhotonPeerListener of this instance (set in constructor).
Can be used in derived classes for Listener.DebugReturn().
Gets count of all bytes coming in (including headers, excluding UDP/TCP overhead)
Gets count of all bytes going out (including headers, excluding UDP/TCP overhead)
Gets the size of the dispatched event or operation-result in bytes.
This value is set before OnEvent() or OnOperationResponse() is called (within DispatchIncomingCommands()).
Get this value directly in OnEvent() or OnOperationResponse(). Example:
void OnEvent(...) {
int eventSizeInBytes = this.peer.ByteCountCurrentDispatch;
//...
void OnOperationResponse(...) {
int resultSizeInBytes = this.peer.ByteCountCurrentDispatch;
//...
Returns the debug string of the event or operation-response currently being dispatched or string. Empty if none.
In a release build of the lib, this will always be empty.
Gets the size of the last serialized operation call in bytes.
The value includes all headers for this single operation but excludes those of UDP, Enet Package Headers and TCP.
Get this value immediately after calling an operation.
Example:
this.loadbalancingClient.OpJoinRoom("myroom");
int opjoinByteCount = this.loadbalancingClient.ByteCountLastOperation;
Gets the byte-count of incoming "low level" messages, which are either Enet Commands or Tcp Messages.
These include all headers, except those of the underlying internet protocol Udp or Tcp.
Gets the byte-count of outgoing "low level" messages, which are either Enet Commands or Tcp Messages.
These include all headers, except those of the underlying internet protocol Udp or Tcp.
Gets a statistic of incoming and outgoing traffic, split by operation, operation-result and event.
Operations are outgoing traffic, results and events are incoming.
Includes the per-command header sizes (Udp: Enet Command Header or Tcp: Message Header).
Returns the count of milliseconds the stats are enabled for tracking.
Enables or disables collection of statistics in TrafficStatsIncoming, TrafficStatsOutgoing and TrafficstatsGameLevel.
Setting this to true, also starts the stopwatch to measure the timespan the stats are collected.
Enables the traffic statistics of a peer: TrafficStatsIncoming, TrafficStatsOutgoing and TrafficstatsGameLevel (nothing else).
Default value: false (disabled).
Creates new instances of TrafficStats and starts a new timer for those.
Size of CommandLog. Default is 0, no logging.
A bigger log is better for debugging but uses more memory.
Get the log as string via CommandLogToString.
Converts the CommandLog into a readable table-like string with summary.
Sent reliable commands begin with SND. Their acknowledgements with ACK.
ACKs list the reliable sequence number of the command they acknowledge (not their own).
Careful: This method should not be called frequently, as it's time- and memory-consuming to create the log.
Up to 4 resend attempts for a reliable command can be done in quick succession (after RTT+4*Variance).
By default 0. Any later resend attempt will then double the time before the next resend.
Max value = 4;
Make sure to adjust SentCountAllowance to a slightly higher value, as more repeats will get done.
This is the (low level) state of the connection to the server of a PhotonPeer. Managed internally and read-only.
Don't mix this up with the StatusCode provided in IPhotonListener.OnStatusChanged().
Applications should use the StatusCode of OnStatusChanged() to track their state, as
it also covers the higher level initialization between a client and Photon.
This peer's ID as assigned by the server or 0 if not using UDP. Will be 0xFFFF before the client connects.
Used for debugging only. This value is not useful in everyday Photon usage.
Initial size internal lists for incoming/outgoing commands (reliable and unreliable).
This sets only the initial size. All lists simply grow in size as needed. This means that
incoming or outgoing commands can pile up and consume heap size if Service is not called
often enough to handle the messages in either direction.
Configure the WarningSize, to get callbacks when the lists reach a certain size.
UDP: Incoming and outgoing commands each have separate buffers for reliable and unreliable sending.
There are additional buffers for "sent commands" and "ACKs".
TCP: Only two buffers exist: incoming and outgoing commands.
(default=2) minimum number of open connections
(default=6) maximum number of open connections, should be > RhttpMinConnections
Limits the queue of received unreliable commands within DispatchIncomingCommands before dispatching them.
This works only in UDP.
This limit is applied when you call DispatchIncomingCommands. If this client (already) received more than
LimitOfUnreliableCommands, it will throw away the older ones instead of dispatching them. This can produce
bigger gaps for unreliable commands but your client catches up faster.
This can be useful when the client couldn't dispatch anything for some time (cause it was in a room but
loading a level).
If set to 20, the incoming unreliable queues are truncated to 20.
If 0, all received unreliable commands will be dispatched.
This is a "per channel" value, so each channel can hold up to LimitOfUnreliableCommands commands.
This value interacts with DispatchIncomingCommands: If that is called less often, more commands get skipped.
Count of all currently received but not-yet-Dispatched reliable commands
(events and operation results) from all channels.
Count of all commands currently queued as outgoing, including all channels and reliable, unreliable.
Gets / sets the number of channels available in UDP connections with Photon.
Photon Channels are only supported for UDP.
The default ChannelCount is 2. Channel IDs start with 0 and 255 is a internal channel.
While not connected, this controls if the next connection(s) should use a per-package CRC checksum.
While turned on, the client and server will add a CRC checksum to every sent package.
The checksum enables both sides to detect and ignore packages that were corrupted during transfer.
Corrupted packages have the same impact as lost packages: They require a re-send, adding a delay
and could lead to timeouts.
Building the checksum has a low processing overhead but increases integrity of sent and received data.
Packages discarded due to failed CRC cecks are counted in PhotonPeer.PacketLossByCrc.
Count of packages dropped due to failed CRC checks for this connection.
Count of packages dropped due to wrong challenge for this connection.
Count of commands that got repeated (due to local repeat-timing before an ACK was received).
The WarningSize is used test all message queues for congestion (in and out, reliable and unreliable).
OnStatusChanged will be called with a warning if a queue holds WarningSize commands or a multiple
of it.
Default: 100.
Example: If command is received, OnStatusChanged will be called when the respective command queue
has 100, 200, 300 ... items.
Number of send retries before a peer is considered lost/disconnected. Default: 7.
The initial timeout countdown of a command is calculated by the current roundTripTime + 4 * roundTripTimeVariance.
Please note that the timeout span until a command will be resent is not constant, but based on
the roundtrip time at the initial sending, which will be doubled with every failed retry.
DisconnectTimeout and SentCountAllowance are competing settings: either might trigger a disconnect on the
client first, depending on the values and Roundtrip Time.
Sets the milliseconds without reliable command before a ping command (reliable) will be sent (Default: 1000ms).
The ping command is used to keep track of the connection in case the client does not send reliable commands
by itself.
A ping (or reliable commands) will update the RoundTripTime calculation.
Milliseconds after which a reliable UDP command triggers a timeout disconnect, unless acknowledged by server.
This value currently only affects UDP connections.
DisconnectTimeout is not an exact value for a timeout. The exact timing of the timeout depends on the frequency
of Service() calls and commands that are sent with long roundtrip-times and variance are checked less often for
re-sending!
DisconnectTimeout and SentCountAllowance are competing settings: either might trigger a disconnect on the
client first, depending on the values and Roundtrip Time.
Default: 10000 ms.
Approximated Environment.TickCount value of server (while connected).
UDP: The server's timestamp is automatically fetched after connecting (once). This is done
internally by a command which is acknowledged immediately by the server.
TCP: The server's timestamp fetched with each ping but set only after connecting (once).
The approximation will be off by +/- 10ms in most cases. Per peer/client and connection, the
offset will be constant (unless FetchServerTimestamp() is used). A constant offset should be
better to adjust for. Unfortunately there is no way to find out how much the local value
differs from the original.
The approximation adds RoundtripTime / 2 and uses this.LocalTimeInMilliSeconds to calculate
in-between values (this property returns a new value per tick).
The value sent by Photon equals Environment.TickCount in the logic layer.
0 until connected.
While connected, the value is an approximation of the server's current timestamp.
The internally used "per connection" time value, which is updated infrequently, when the library executes some connectio-related tasks.
This integer value is an infrequently updated value by design.
The lib internally sets the value when it sends outgoing commands or reads incoming packages.
This is based on SupportClass.GetTickCount() and an initial time value per (server) connection.
This value is also used in low level Enet commands as sent time and optional logging.
The last ConnectionTime value, when some ACKs were sent out by this client.
Only applicable to UDP connections.
The last ConnectionTime value, when SendOutgoingCommands actually checked outgoing queues to send them. Must be connected.
Available for UDP and TCP connections.
Gets a local timestamp in milliseconds by calling SupportClass.GetTickCount().
See LocalMsTimestampDelegate.
This setter for the (local-) timestamp delegate replaces the default Environment.TickCount with any equal function.
About Environment.TickCount:
The value of this property is derived from the system timer and is stored as a 32-bit signed integer.
Consequently, if the system runs continuously, TickCount will increment from zero to Int32..::.MaxValue
for approximately 24.9 days, then jump to Int32..::.MinValue, which is a negative number, then increment
back to zero during the next 24.9 days.
Exception is thrown peer.PeerState is not PS_DISCONNECTED.
Time until a reliable command is acknowledged by the server.
The value measures network latency and for UDP it includes the server's ACK-delay (setting in config).
In TCP, there is no ACK-delay, so the value is slightly lower (if you use default settings for Photon).
RoundTripTime is updated constantly. Every reliable command will contribute a fraction to this value.
This is also the approximate time until a raised event reaches another client or until an operation
result is available.
Changes of the roundtriptime as variance value. Gives a hint about how much the time is changing.
Stores timestamp of the last time anything (!) was received from the server (including
low level Ping and ACKs but also events and operation-returns). This is not the time when
something was dispatched.
If you enable NetworkSimulation, this value is affected as well.
The server address which was used in PhotonPeer.Connect() or null (before Connect() was called).
The ServerAddress can only be changed for HTTP connections (to replace one that goes through a Loadbalancer with a direct URL).
The protocol this peer is currently connected/connecting with (or 0).
This is the protocol to be used for next connect (see remarks).
The TransportProtocol can be changed anytime but it will not change the protocol
of currently active connections. Instead, TransportProtocol will be applied on next Connect.
Gets or sets the network simulation "enabled" setting.
Changing this value also locks this peer's sending and when setting false,
the internally used queues are executed (so setting to false can take some cycles).
Gets the settings for built-in Network Simulation for this peer instance
while IsSimulationEnabled will enable or disable them.
Once obtained, the settings can be modified by changing the properties.
Defines the initial size of an internally used StreamBuffer for Tcp.
The StreamBuffer is used to aggregate operation into (less) send calls,
which uses less resoures.
The size is not restricing the buffer and does not affect when poutgoing data is actually sent.
The Maximum Trasfer Unit (MTU) defines the (network-level) packet-content size that is
guaranteed to arrive at the server in one piece. The Photon Protocol uses this
size to split larger data into packets and for receive-buffers of packets.
This value affects the Packet-content. The resulting UDP packages will have additional
headers that also count against the package size (so it's bigger than this limit in the end)
Setting this value while being connected is not allowed and will throw an Exception.
Minimum is 576. Huge values won't speed up connections in most cases!
This property is set internally, when OpExchangeKeysForEncryption successfully finished.
While it's true, encryption can be used for operations.
While true, the peer will not send any other commands except ACKs (used in UDP connections).
Implements the message-protocol, based on the underlying network protocol (udp, tcp, http).
Creates a new PhotonPeer instance to communicate with Photon and selects either UDP or TCP as
protocol. We recommend UDP.
a IPhotonPeerListener implementation
Protocol to use to connect to Photon.
This method does a DNS lookup (if necessary) and connects to the given serverAddress.
The return value gives you feedback if the address has the correct format. If so, this
starts the process to establish the connection itself, which might take a few seconds.
When the connection is established, a callback to IPhotonPeerListener.OnStatusChanged
will be done. If the connection can't be established, despite having a valid address,
the OnStatusChanged is called with an error-value.
The applicationName defines the application logic to use server-side and it should match the name of
one of the apps in your server's config.
By default, the applicationName is "LoadBalancing" but there is also the "MmoDemo".
You can setup your own application and name it any way you like.
Address of the Photon server. Format: ip:port (e.g. 127.0.0.1:5055) or hostname:port (e.g. localhost:5055)
The name of the application to use within Photon or the appId of PhotonCloud.
Should match a "Name" for an application, as setup in your PhotonServer.config.
true if IP is available (DNS name is resolved) and server is being connected. false on error.
This method does a DNS lookup (if necessary) and connects to the given serverAddress.
The return value gives you feedback if the address has the correct format. If so, this
starts the process to establish the connection itself, which might take a few seconds.
When the connection is established, a callback to IPhotonPeerListener.OnStatusChanged
will be done. If the connection can't be established, despite having a valid address,
the OnStatusChanged is called with an error-value.
The applicationName defines the application logic to use server-side and it should match the name of
one of the apps in your server's config.
By default, the applicationName is "LoadBalancing" but there is also the "MmoDemo".
You can setup your own application and name it any way you like.
Address of the Photon server. Format: ip:port (e.g. 127.0.0.1:5055) or hostname:port (e.g. localhost:5055)
The name of the application to use within Photon or the appId of PhotonCloud.
Should match a "Name" for an application, as setup in your PhotonServer.config.
Allows you to send some data, which may be used by server during peer creation
(e.g. as additional authentication info).
You can use any serializable data type of Photon.
Helpful for self-hosted solutions. Server will read this info on peer creation stage,
and may reject client without creating of peer if auth info is invalid.
true if IP is available (DNS name is resolved) and server is being connected. false on error.
This method initiates a mutual disconnect between this client and the server.
Calling this method does not immediately close a connection. Disconnect lets the server
know that this client is no longer listening. For the server, this is a much faster way
to detect that the client is gone but it requires the client to send a few final messages.
On completion, OnStatusChanged is called with the StatusCode.Disconnect.
If the client is disconnected already or the connection thread is stopped, then there is no callback.
The default server logic will leave any joined game and trigger the respective event
() for the remaining players.
This method immediately closes a connection (pure client side) and ends related listening Threads.
Unlike Disconnect, this method will simply stop to listen to the server. Udp connections will timeout.
If the connections was open, this will trigger a callback to OnStatusChanged with code StatusCode.Disconnect.
This will fetch the server's timestamp and update the approximation for property ServerTimeInMilliseconds.
The server time approximation will NOT become more accurate by repeated calls. Accuracy currently depends
on a single roundtrip which is done as fast as possible.
The command used for this is immediately acknowledged by the server. This makes sure the roundtrip time is
low and the timestamp + rountriptime / 2 is close to the original value.
This method creates a public key for this client and exchanges it with the server.
Encryption is not instantly available but calls OnStatusChanged when it finishes.
Check for StatusCode EncryptionEstablished and EncryptionFailedToEstablish.
Calling this method sets IsEncryptionAvailable to false.
This method must be called before the "encrypt" parameter of OpCustom can be used.
If operation could be enqueued for sending
PayloadEncryption Secret. Message payloads get encrypted with it individually and on demand.
Initializes Datagram Encryption.
secret used to chipher udp packets
secret used for authentication of udp packets
This method excutes DispatchIncomingCommands and SendOutgoingCommands in your application Thread-context.
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 remaining buffered responses 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
This method creates a UDP/TCP package for outgoing commands (operations and acknowledgements)
and sends them to the server.
This method is also called by Service().
As the Photon library does not create any UDP/TCP packages by itself. Instead, the application
fully controls how many packages are sent and when. A tradeoff, an application will
lose connection, if it is no longer calling SendOutgoingCommands or Service.
If multiple operations and ACKs are waiting to be sent, they will be aggregated into one
package. The package fills in this order:
ACKs for received commands
A "Ping" - only if no reliable data was sent for a while
Starting with the lowest Channel-Nr:
Reliable Commands in channel
Unreliable Commands in channel
This gives a higher priority to lower channels.
A longer interval between sends will lower the overhead per sent operation but
increase the internal delay (which adds "lag").
Call this 2..20 times per second (depending on your target platform).
The if commands are not yet sent. Udp limits it's package size, Tcp doesnt.
This method directly causes the callbacks for events, responses and state changes
within a IPhotonPeerListener. DispatchIncomingCommands only executes a single received
command per call. If a command was dispatched, the return value is true and the method
should be called again.
This method is called by Service() until currently available commands are dispatched.
In general, this method should be called until it returns false. In a few cases, it might
make sense to pause dispatching (if a certain state is reached and the app needs to load
data, before it should handle new events).
The callbacks to the peer's IPhotonPeerListener are executed in the same thread that is
calling DispatchIncomingCommands. This makes things easier in a game loop: Event execution
won't clash with painting objects or the game logic.
Returns a string of the most interesting connection statistics.
When you have issues on the client side, these might contain hints about the issue's cause.
If true, Incoming and Outgoing low-level stats are included in the string.
Stats as string.
Channel-less wrapper for OpCustom().
Operations are handled by their byte\-typed code.
The codes of the "LoadBalancong" application are in the class .
Containing parameters as key\-value pair. The key is byte\-typed, while the value is any serializable datatype.
Selects if the operation must be acknowledged or not. If false, the
operation is not guaranteed to reach the server.
If operation could be enqueued for sending
Allows the client to send any operation to the Photon Server by setting any opCode and the operation's parameters.
Photon can be extended with new operations which are identified by a single
byte, defined server side and known as operation code (opCode). Similarly, the operation's parameters
are defined server side as byte keys of values, which a client sends as customOpParameters
accordingly.
Operations are handled by their byte\-typed code. The codes of the
"LoadBalancing" application are in the class .
Containing parameters as key\-value pair. The key is byte\-typed, while the value is any serializable datatype.
Selects if the operation must be acknowledged or not. If false, the
operation is not guaranteed to reach the server.
The channel in which this operation should be sent.
If operation could be enqueued for sending
Allows the client to send any operation to the Photon Server by setting any opCode and the operation's parameters.
Variant with encryption parameter.
Use this only after encryption was established by EstablishEncryption and waiting for the OnStateChanged callback.
Operations are handled by their byte\-typed code. The codes of the
"LoadBalancing" application are in the class .
Containing parameters as key\-value pair. The key is byte\-typed, while the value is any serializable datatype.
Selects if the operation must be acknowledged or not. If false, the
operation is not guaranteed to reach the server.
The channel in which this operation should be sent.
Can only be true, while IsEncryptionAvailable is true, too.
If operation could be enqueued for sending
Allows the client to send any operation to the Photon Server by setting any opCode and the operation's parameters.
Variant with an OperationRequest object.
This variant offers an alternative way to describe a operation request. Operation code and it's parameters
are wrapped up in a object. Still, the parameters are a Dictionary.
The operation to call on Photon.
Use unreliable (false) if the call might get lost (when it's content is soon outdated).
Defines the sequence of requests this operation belongs to.
Encrypt request before sending. Depends on IsEncryptionAvailable.
If operation could be enqueued for sending
Registers new types/classes for de/serialization and the fitting methods to call for this type.
SerializeMethod and DeserializeMethod are complementary: Feed the product of serializeMethod to
the constructor, to get a comparable instance of the object.
After registering a Type, it can be used in events and operations and will be serialized like
built-in types.
Type (class) to register.
A byte-code used as shortcut during transfer of this Type.
Method delegate to create a byte[] from a customType instance.
Method delegate to create instances of customType's from byte[].
If the Type was registered successfully.
Param code. Used in internal op: InitEncryption.
Encryption-Mode code. Used in internal op: InitEncryption.
Param code. Used in internal op: InitEncryption.
Code of internal op: InitEncryption.
TODO: Code of internal op: Ping (used in PUN binary websockets).
Result code for any (internal) operation.
Byte count of last sent operation (set during serialization).
Byte count of last dispatched message (set during dispatch/deserialization).
The command that's currently being dispatched.
EnetPeer will set this value, so trafficstats can use it. TCP has 0 bytes per package extra
See PhotonPeer value.
See PhotonPeer value.
See PhotonPeer value.
See PhotonPeer value.
This ID is assigned by the Realtime Server upon connection.
The application does not have to care about this, but it is useful in debugging.
This is the (low level) connection state of the peer. It's internal and based on eNet's states.
Applications can read the "high level" state as PhotonPeer.PeerState, which uses a different enum.
The serverTimeOffset is serverTimestamp - localTime. Used to approximate the serverTimestamp with help of localTime
Gets the currently used settings for the built-in network simulation.
Please check the description of NetworkSimulationSet for more details.
Size of CommandLog. Default is 0, no logging.
Log of sent reliable commands and incoming ACKs.
Log of incoming reliable commands, used to track which commands from the server this client got. Part of the PhotonPeer.CommandLogToString() result.
Reduce CommandLog to CommandLogSize. Oldest entries get discarded.
Initializes the CommandLog and InReliableLog according to CommandLogSize. A value of 0 will set both logs to 0.
Converts the CommandLog into a readable table-like string with summary.
Count of all bytes going out (including headers)
Count of all bytes coming in (including headers)
Set via Connect(..., customObject) and sent in Init-Request.
Temporary cache of AppId. Used in Connect() to keep the AppId until we send the Init-Request (after the network-level (and Enet) connect).
This is the replacement for the const values used in eNet like: PS_DISCONNECTED, PS_CONNECTED, etc.
No connection is available. Use connect.
Establishing a connection already. The app should wait for a status callback.
The low level connection with Photon is established. On connect, the library will automatically
send an Init package to select the application it connects to (see also PhotonPeer.Connect()).
When the Init is done, IPhotonPeerListener.OnStatusChanged() is called with connect.
Please note that calling operations is only possible after the OnStatusChanged() with StatusCode.Connect.
Connection going to be ended. Wait for status callback.
Acknowledging a disconnect from Photon. Wait for status callback.
Connection not properly disconnected.
Set to timeInt, whenever SendOutgoingCommands actually checks outgoing queues to send them. Must be connected.
Connect to server and send Init (which inlcudes the appId).
If customData is not null, the new init will be used (http-based).
If IPhotonSocket.Connected is true, this value shows if the server's address resolved as IPv6 address.
You must check the socket's IsConnected state. Otherwise, this value is not initialized.
Sent to server in Init-Request.
Must be called by a IPhotonSocket when it connected to set IsIpv6.
The new value of IsIpv6.
Checks the incoming queue and Dispatches received data if possible.
If a Dispatch happened or not, which shows if more Dispatches might be needed.
Checks outgoing queues for commands to send and puts them on their way.
This creates one package per go in UDP.
If commands are not sent, cause they didn't fit into the package that's sent.
Returns the UDP Payload starting with Magic Number for binary protocol
Returns the UDP Payload starting with Magic Number for binary protocol
Maximum Transfer Unit to be used for UDP+TCP
(default=2) Rhttp: minimum number of open connections
(default=6) Rhttp: maximum number of open connections, should be > rhttpMinConnections
Internally uses an operation to exchange encryption keys with the server.
If the op could be sent.
Core of the Network Simulation, which is available in Debug builds.
Called by a timer in intervals.
Will contain channel 0xFF and any other.
One list for all channels keeps sent commands (for re-sending).
One list for all channels keeps acknowledgements.
Gets enabled by "request" from server (not by client).
Checks the incoming queue and Dispatches received data if possible.
If a Dispatch happened or not, which shows if more Dispatches might be needed.
gathers acks until udp-packet is full and sends it!
gathers commands from all (out)queues until udp-packet is full and sends it!
Checks if any channel has a outgoing reliable command.
True if any channel has a outgoing reliable command. False otherwise.
Checks connected state and channel before operation is serialized and enqueued for sending.
operation parameters
code of operation
send as reliable command
channel (sequence) for command
encrypt or not
usually EgMessageType.Operation
if operation could be enqueued
reliable-udp-level function to send some byte[] to the server via un/reliable command
only called when a custom operation should be send
(enet) command type
data to carry (operation)
channel in which to send
the invocation ID for this operation (the payload)
Returns the UDP Payload starting with Magic Number for binary protocol
reads incoming udp-packages to create and queue incoming commands*
queues incoming commands in the correct order as either unreliable, reliable or unsequenced. return value determines if the command is queued / done.
removes commands which are acknowledged*
Internal class for "commands" - the package in which operations are sent.
this variant does only create outgoing commands and increments . incoming ones are created from a DataInputStream
reads the command values (commandHeader and command-values) from incoming bytestream and populates the incoming command*
TCP "Package" header: 7 bytes
TCP "Message" header: 2 bytes
TCP header combined: 9 bytes
Defines if the (TCP) socket implementation needs to do "framing".
The WebSocket protocol (e.g.) includes framing, so when that is used, we set DoFraming to false.
Checks the incoming queue and Dispatches received data if possible. Returns if a Dispatch happened or
not, which shows if more Dispatches might be needed.
gathers commands from all (out)queues until udp-packet is full and sends it!
Sends a ping in intervals to keep connection alive (server will timeout connection if nothing is sent).
Always false in this case (local queues are ignored. true would be: "call again to send remaining data").
Returns the UDP Payload starting with Magic Number for binary protocol
enqueues serialized operations to be sent as tcp stream / package
Sends a ping and modifies this.lastPingResult to avoid another ping for a while.
reads incoming tcp-packages to create and queue incoming commands*
Container for an Operation request, which is a code and parameters.
On the lowest level, Photon only allows byte-typed keys for operation parameters.
The values of each such parameter can be any serializable datatype: byte, int, hashtable and many more.
Byte-typed code for an operation - the short identifier for the server's method to call.
The parameters of the operation - each identified by a byte-typed code in Photon.
Contains the server's response for an operation called by this peer.
The indexer of this class actually provides access to the Parameters Dictionary.
The OperationCode defines the type of operation called on Photon and in turn also the Parameters that
are set in the request. Those are provided as Dictionary with byte-keys.
There are pre-defined constants for various codes defined in the LoadBalancing application.
Check: OperationCode, ParameterCode, etc.
An operation's request is summarized by the ReturnCode: a short typed code for "Ok" or
some different result. The code's meaning is specific per operation. An optional DebugMessage can be
provided to simplify debugging.
Each call of an operation gets an ID, called the "invocID". This can be matched to the IDs
returned with any operation calls. This way, an application could track if a certain OpRaiseEvent
call was successful.
The code for the operation called initially (by this peer).
Use enums or constants to be able to handle those codes, like OperationCode does.
A code that "summarizes" the operation's success or failure. Specific per operation. 0 usually means "ok".
An optional string sent by the server to provide readable feedback in error-cases. Might be null.
A Dictionary of values returned by an operation, using byte-typed keys per value.
Alternative access to the Parameters, which wraps up a TryGetValue() call on the Parameters Dictionary.
The byte-code of a returned value.
The value returned by the server, or null if the key does not exist in Parameters.
ToString() override.
Relatively short output of OpCode and returnCode.
Extensive output of operation results.
To be used in debug situations only, as it returns a string for each value.
Contains all components of a Photon Event.
Event Parameters, like OperationRequests and OperationResults, consist of a Dictionary with byte-typed keys per value.
The indexer of this class provides access to the Parameters Dictionary.
The operation RaiseEvent allows you to provide custom event content. Defined in LoadBalancing, this
CustomContent will be made the value of key ParameterCode.CustomEventContent.
The event code identifies the type of event.
The Parameters of an event is a Dictionary<byte, object>.
Alternative access to the Parameters.
The key byte-code of a event value.
The Parameters value, or null if the key does not exist in Parameters.
ToString() override.
Short output of "Event" and it's Code.
Extensive output of the event content.
To be used in debug situations only, as it returns a string for each value.
Type of serialization methods to add custom type support.
Use PhotonPeer.ReisterType() to register new types with serialization and deserialization methods.
The method will get objects passed that were registered with it in RegisterType().
Return a byte[] that resembles the object passed in. The framework will surround it with length and type info, so don't include it.
Type of deserialization methods to add custom type support.
Use PhotonPeer.RegisterType() to register new types with serialization and deserialization methods.
The framwork passes in the data it got by the associated SerializeMethod. The type code and length are stripped and applied before a DeserializeMethod is called.
Return a object of the type that was associated with this method through RegisterType().
Provides tools for the Exit Games Protocol
Serialize creates a byte-array from the given object and returns it.
The object to serialize
The serialized byte-array
Deserialize returns an object reassembled from the given byte-array.
The byte-array to be Deserialized
The Deserialized object
Serializes a short typed value into a byte-array (target) starting at the also given targetOffset.
The altered offset is known to the caller, because it is given via a referenced parameter.
The short value to be serialized
The byte-array to serialize the short to
The offset in the byte-array
Serializes an int typed value into a byte-array (target) starting at the also given targetOffset.
The altered offset is known to the caller, because it is given via a referenced parameter.
The int value to be serialized
The byte-array to serialize the short to
The offset in the byte-array
Serializes an float typed value into a byte-array (target) starting at the also given targetOffset.
The altered offset is known to the caller, because it is given via a referenced parameter.
The float value to be serialized
The byte-array to serialize the short to
The offset in the byte-array
Deserialize fills the given int typed value with the given byte-array (source) starting at the also given offset.
The result is placed in a variable (value). There is no need to return a value because the parameter value is given by reference.
The altered offset is this way also known to the caller.
The int value to deserialize into
The byte-array to deserialize from
The offset in the byte-array
Deserialize fills the given short typed value with the given byte-array (source) starting at the also given offset.
The result is placed in a variable (value). There is no need to return a value because the parameter value is given by reference.
The altered offset is this way also known to the caller.
The short value to deserialized into
The byte-array to deserialize from
The offset in the byte-array
Deserialize fills the given float typed value with the given byte-array (source) starting at the also given offset.
The result is placed in a variable (value). There is no need to return a value because the parameter value is given by reference.
The altered offset is this way also known to the caller.
The float value to deserialize
The byte-array to deserialize from
The offset in the byte-array
Exit Games GpBinaryV16 protocol implementation
The gp type.
Unkown type.
An array of objects.
This type is new in version 1.5.
A boolean Value.
A byte value.
An array of bytes.
An array of objects.
A 16-bit integer value.
A 32-bit floating-point value.
This type is new in version 1.5.
A dictionary
This type is new in version 1.6.
A 64-bit floating-point value.
This type is new in version 1.5.
A Hashtable.
A 32-bit integer value.
An array of 32-bit integer values.
A 64-bit integer value.
A string value.
An array of string values.
A costum type
Null value don't have types.
Calls the correct serialization method for the passed object.
DeserializeInteger returns an Integer typed value from the given stream.
Uses C# Socket class from System.Net.Sockets (as Unity usually does).
Incompatible with Windows 8 Store/Phone API.
Sends a "Photon Ping" to a server.
Address in IPv4 or IPv6 format. An address containing a '.' will be interpretet as IPv4.
True if the Photon Ping could be sent.
Separates the given address into address (host name or IP) and port. Port must be included after colon!
This method expects any address to include a port. The final ':' in addressAndPort has to separate it.
IPv6 addresses have multiple colons and must use brackets to separate address from port.
Examples:
ns.exitgames.com:5058
http://[2001:db8:1f70::999:de8:7648:6e8]:100/
[2001:db8:1f70::999:de8:7648:6e8]:100
See:
http://serverfault.com/questions/205793/how-can-one-distinguish-the-host-and-the-port-in-an-ipv6-url
Implements a (very) simple test if a (valid) IPAddress is IPv6 by testing for colons (:).
The reason we use this, is that some DotNet platforms don't provide (or allow usage of) the System.Net namespace.
A valid IPAddress or null.
If the IPAddress.ToString() contains a colon (which means it's IPv6).
Returns null or the IPAddress representing the address, doing Dns resolution if needed.
Only returns IPv4 or IPv6 adresses, no others.
The string address of a server (hostname or IP).
IPAddress for the string address or null, if the address is neither IPv4, IPv6 or some hostname that could be resolved.
Internal class to encapsulate the network i/o functionality for the realtime libary.
used by PhotonPeer*
Endless loop, run in Receive Thread.
Internal class to encapsulate the network i/o functionality for the realtime libary.
used by TPeer*
A simulation item is an action that can be queued to simulate network lag.
With this, the actual delay can be measured, compared to the intended lag.
Timestamp after which this item must be executed.
Action to execute when the lag-time passed.
Starts a new Stopwatch
A set of network simulation settings, enabled (and disabled) by PhotonPeer.IsSimulationEnabled.
For performance reasons, the lag and jitter settings can't be produced exactly.
In some cases, the resulting lag will be up to 20ms bigger than the lag settings.
Even if all settings are 0, simulation will be used. Set PhotonPeer.IsSimulationEnabled
to false to disable it if no longer needed.
All lag, jitter and loss is additional to the current, real network conditions.
If the network is slow in reality, this will add even more lag.
The jitter values will affect the lag positive and negative, so the lag settings
describe the medium lag even with jitter. The jitter influence is: [-jitter..+jitter].
Packets "lost" due to OutgoingLossPercentage count for BytesOut and LostPackagesOut.
Packets "lost" due to IncomingLossPercentage count for BytesIn and LostPackagesIn.
internal
internal
internal
internal
internal
internal
internal
This setting overrides all other settings and turns simulation on/off. Default: false.
Outgoing packages delay in ms. Default: 100.
Randomizes OutgoingLag by [-OutgoingJitter..+OutgoingJitter]. Default: 0.
Percentage of outgoing packets that should be lost. Between 0..100. Default: 1. TCP ignores this setting.
Incoming packages delay in ms. Default: 100.
Randomizes IncomingLag by [-IncomingJitter..+IncomingJitter]. Default: 0.
Percentage of incoming packets that should be lost. Between 0..100. Default: 1. TCP ignores this setting.
Counts how many outgoing packages actually got lost. TCP connections ignore loss and this stays 0.
Counts how many incoming packages actually got lost. TCP connections ignore loss and this stays 0.
Only in use as long as PhotonPeer.TrafficStatsEnabled = true;
Gets sum of outgoing operations in bytes.
Gets count of outgoing operations.
Gets sum of byte-cost of incoming operation-results.
Gets count of incoming operation-results.
Gets sum of byte-cost of incoming events.
Gets count of incoming events.
Gets longest time it took to complete a call to OnOperationResponse (in your code).
If such a callback takes long, it will lower the network performance and might lead to timeouts.
Gets OperationCode that causes the LongestOpResponseCallback. See that description.
Gets longest time a call to OnEvent (in your code) took.
If such a callback takes long, it will lower the network performance and might lead to timeouts.
Gets EventCode that caused the LongestEventCallback. See that description.
Gets longest time between subsequent calls to DispatchIncomgingCommands in milliseconds.
Note: This is not a crucial timing for the networking. Long gaps just add "local lag" to events that are available already.
Gets longest time between subsequent calls to SendOutgoingCommands in milliseconds.
Note: This is a crucial value for network stability. Without calling SendOutgoingCommands,
nothing will be sent to the server, who might time out this client.
Gets number of calls of DispatchIncomingCommands.
Gets number of calls of DispatchIncomingCommands.
Gets number of calls of SendOutgoingCommands.
Gets sum of byte-cost of all "logic level" messages.
Gets sum of counted "logic level" messages.
Gets sum of byte-cost of all incoming "logic level" messages.
Gets sum of counted incoming "logic level" messages.
Gets sum of byte-cost of all outgoing "logic level" messages (= OperationByteCount).
Gets sum of counted outgoing "logic level" messages (= OperationCount).
Resets the values that can be maxed out, like LongestDeltaBetweenDispatching. See remarks.
Set to 0: LongestDeltaBetweenDispatching, LongestDeltaBetweenSending, LongestEventCallback, LongestEventCallbackCode, LongestOpResponseCallback, LongestOpResponseCallbackOpCode.
Also resets internal values: timeOfLastDispatchCall and timeOfLastSendCall (so intervals are tracked correctly).
Gets the byte-size of per-package headers.
Counts commands created/received by this client, ignoring repeats (out command count can be higher due to repeats).
Gets count of bytes as traffic, excluding UDP/TCP headers (42 bytes / x bytes).
Timestamp of the last incoming ACK that has been read (every PhotonPeer.TimePingInterval milliseconds this client sends a PING which must be ACKd).
Timestamp of last incoming reliable command (every second we expect a PING).
Serialize creates a byte-array from the given object and returns it.
The object to serialize
The serialized byte-array
Deserialize returns an object reassembled from the given byte-array.
The byte-array to be Deserialized
The Deserialized object
Provides classical Diffie-Hellman Modular Exponentiation Groups defined by the
OAKLEY Key Determination Protocol (RFC 2412).
Gets the genrator (N) used by the the well known groups 1,2 and 5.
Gets the 768 bit prime for the well known group 1.
Gets the 1024 bit prime for the well known group 2.
Gets the 1536 bit prime for the well known group 5.
Initializes a new instance of the class.
Gets the public key that can be used by another DiffieHellmanCryptoProvider object
to generate a shared secret agreement.
Derives the shared key is generated from the secret agreement between two parties,
given a byte array that contains the second party's public key.
The second party's public key.