Friday, June 10, 2011

Foray into Photon - Part 3 Operations

It took me a while to understand what Photon meant when they said Events and Operations. I ran across their glossary and it says this:

Event - Events are asynchronous messages sent to clients. They can be triggered by operations (as sideeffect) or raised (as main purpose of an operation) and are identified by an event code. The origin is identified as ActorNumber.

Operation - Another word for RPC functions on the Photon server side. Clients use operations to do anything on the server and even to send events to others.

So in Unity3D we send operations to the server, and we receive events from the server and then sender receives an OperationResponse which tells us what happened according to the server. This can be a simple OK message meaning it was successful, or it could be an error with something like the operation cannot be processed.

So there is one change we need to make on the server to return to us a message so we know the server got our request. If you open up AegisBornPeer the return statement of OnOperationRequest should be changed to:


            return new OperationResponse(operationRequest, 0, "Ok", new Dictionary { {100, "We get signal." } });

Build the server and then head back into unity3d. In the OnGUI of Login we add this line under the first button:

            if (GUI.Button(new Rect(200, 60, 100, 30), "Send Operation"))
            {
                engine.sendOp();
            }

With that in place, jump over to Game and lets create the function.

    public void sendOp()
    {
        peer.OpCustom(100, new Hashtable(), true, 0);
    }

This creates an Operation, gives it an OpCode of 100 and sends no data. It sends it reliably and uses channel 0. Channels are like telephone lines. Lets say you have 3 channels. each channel operates independently of each other. All events and operations on a channel are guaranteed to be in order. 

Lastly we need to do something when we get our OperationResult. I chose to read through the return values for an item numbered 100 and display the string contained there:

     public void OperationResult(byte opCode, int returnCode, System.Collections.Hashtable returnValues, short invocID)
    {
        var debug = (string)returnValues[(byte)100];

        status = debug;
    }

This concludes this section. if you run the code, you can click the connect button to connect to the server and then send an operations which returns an OperationResult that contains the message "We get signal". This concludes this small section. Next we will look at using the OperationDispatcher to handle multiple operations without having to use a giant switch statement.

No comments: