Create a NetConnection object and connect to the server:
Before you create a remote shared object, create a NetConnection object and connect to the server. Once you have the connection, use the methods in the SharedObject class to create and update the remote shared object. The general sequence of steps for using a remote shared object is outlined below:
-
nc = new NetConnection(); nc.connect("rtmp://localhost/SharedBall");
This is the simplest way to connect to the server. In a real application, you would add event listeners on the NetConnection object and define event handler methods. For more information, see SharedBall example.
-
Create the remote shared object. When the connection is successful, call SharedObject.getRemote() to create a remote shared object on the server:
so = SharedObject.getRemote("ballPosition", nc.uri, false);
The first parameter is the name of the remote shared object. The second is the URI of the application you are connecting to and must be identical to the URI used in the NetConnection.connect() method. The easiest way to specify it is with the nc.uri property. The third parameter specifies whether the remote shared object is persistent. In this case, false is used to make the shared object temporary.
-
Connect to the remote shared object. Once the shared object is created, connect the client to the shared object using the NetConnection object you just created:
so.connect(nc);
You also need to add an event listener for sync events dispatched by the shared object:
so.addEventListener(SyncEvent.SYNC, syncHandler);
-
Synchronize the remote shared object with clients. Synchronizing the remote shared object requires two steps. First, when an individual client makes a change or sets a data value, you need to update the remote shared object. Next, update all other clients from the remote shared object.
-
To update the remote shared object when a client makes a change, use setProperty():
so.setProperty("x", sharedBall.x);
You must use setProperty() to update values in the shared object. The remote shared object has a data property that contains attributes and values. However, in ActionScript 3.0, you cannot write values directly to it, as in:
so.data.x = sharedBall.x; // you can’t do this
-
When the shared object is updated, it dispatches a sync event. Synchronize the change to the remaining clients by reading the value of the shared object’s data property:
sharedBall.x = so.data.x;
This is usually done in a sync event handler, as shown in SharedBall example.
-