Connecting to other Flash Player instances

The LocalConnection class lets you communicate between different Flash Player instances, such as a SWF in an HTML container or in an embedded or stand-alone player. This allows you to build very versatile applications that can share data between Flash Player instances, such as SWF files running in a web browser or embedded in desktop applications.

Subtopics

LocalConnection class
Sending messages between two Flash Player instances
Connecting to SWF documents in different domains

LocalConnection class

The LocalConnection class lets you develop SWF files that can send instructions to other SWF files without the use of the fscommand() method or JavaScript. LocalConnection objects can communicate only among SWF files that are running on the same client computer, but they can run in different applications. For example, a SWF file running in a browser and a SWF file running in a projector can share information, with the projector maintaining local information and the browser-based SWF connecting remotely. (A projector is a SWF file saved in a format that can run as a stand-alone application--that is, the projector doesn't require Flash Player to be installed because it is embedded inside the executable.)

LocalConnection objects can be used to communicate between SWFs using different ActionScript versions:

Flash Player handles this communication between LocalConnection objects of different versions automatically.

The simplest way to use a LocalConnection object is to allow communication only between LocalConnection objects located in the same domain. That way, you won't have to worry about security issues. However, if you need to allow communication between domains, you have several ways to implement security measures. For more information, see the discussion of the connectionName parameter of the send() method and the allowDomain() and domain entries in the LocalConnection class listing in the ActionScript 3.0 Language and Components Reference.

TIP

 

It is possible to use LocalConnection objects to send and receive data within a single SWF file, but Adobe does not recommended doing so. Instead, you should use shared objects.

There are three ways to add callback methods to your LocalConnection objects:

The first way to add callback methods is to extend the LocalConnection class. You define the methods within the custom class instead of dynamically adding them to the LocalConnection instance. This approach is demonstrated in the following code:

package
{
    import flash.net.LocalConnection;
    public class CustomLocalConnection extends LocalConnection
    {
        public function CustomLocalConnection(connectionName:String)
        {
            try
            {
                connect(connectionName);
            }
            catch (error:ArgumentError)
            {
                // server already created/connected
            }
        }
        public function onMethod(timeString:String):void
        {
            trace("onMethod called at: " + timeString);
        }
    }
}

In order to create a new instance of the DynamicLocalConnection class, you can use the following code:

var serverLC:CustomLocalConnection;
serverLC = new CustomLocalConnection("serverName");

The second way to add callback methods is to use the LocalConnection.client property. This involves creating a custom class and assigning a new instance to the client property, as the following code shows:

var lc:LocalConnection = new LocalConnection();
lc.client = new CustomClient();

The LocalConnection.client property indicates the object callback methods that should be invoked. In the previous code, the client property was set to a new instance of a custom class, CustomClient. The default value for the client property is the current LocalConnection instance. You can use the client property if you have two data handlers that have the same set of methods but act differently--for example, in an application where a button in one window toggles the view in a second window.

To create the CustomClient class, you could use the following code:

package
{
    public class CustomClient extends Object
    {
        public function onMethod(timeString:String):void
        {
            trace("onMethod called at: " + timeString);
        }
    }
}

The third way to add callback methods, creating a dynamic class and dynamically attaching the methods, is very similar to using the LocalConnection class in earlier versions of ActionScript, as the following code shows:

import flash.net.LocalConnection;
dynamic class DynamicLocalConnection extends LocalConnection {}

Callback methods can be dynamically added to this class by using the following code:

var connection:DynamicLocalConnection = new DynamicLocalConnection();
connection.onMethod = this.onMethod;
// Add your code here.
public function onMethod(timeString:String):void
{
    trace("onMethod called at: " + timeString);
}

The previous way of adding callback methods is not recommended because the code is not very portable. In addition, using this method of creating local connections could create performance issues, because accessing dynamic properties is dramatically slower than accessing sealed properties.

Sending messages between two Flash Player instances

You use the LocalConnection class to communicate between different instances of Flash Player. For example, you could have multiple Flash Player instances on a web page, or have a Flash Player instance retrieve data from a Flash Player instance in a pop-up window.

The following code defines a local connection object that acts as a server and accepts incoming calls from other Flash Player instances:

package
{
    import flash.net.LocalConnection;
    import flash.display.Sprite;
    public class ServerLC extends Sprite
    {
        public function ServerLC()
        {
            var lc:LocalConnection = new LocalConnection();
            lc.client = new CustomClient1();
            try
            {
                lc.connect("conn1");
            }
            catch (error:Error)
            {
                trace("error:: already connected");
            }
        }
    }
}

This code first creates a LocalConnection object named lc and sets the client property to a custom class, CustomClient1. When another Flash Player instance calls a method in this local connection instance, Flash Player looks for that method in the CustomClient1 class.

Whenever a Flash Player instance connects to this SWF file and tries to invoke any method for the specified local connection, the request is sent to the class specified by the client property, which is set to the CustomClient1 class:

package
{
    import flash.events.*;
    import flash.system.fscommand;
    import flash.utils.Timer;
    public class CustomClient1 extends Object
    {
        public function doMessage(value:String = ""):void
        {
            trace(value);
        }
        public function doQuit():void
        {
            trace("quitting in 5 seconds");
            this.close();
            var quitTimer:Timer = new Timer(5000, 1);
            quitTimer.addEventListener(TimerEvent.TIMER, closeHandler);
        }
        public function closeHandler(event:TimerEvent):void
        {
            fscommand("quit");
        }
    }
}

To create a LocalConnection server, call the LocalConnection.connect() method and provide a unique connection name. If you already have a connection with the specified name, an ArgumentError error is generated, indicating that the connection attempt failed because the object is already connected.

The following snippet demonstrates how to create a new socket connection with the name conn1:

try
{
    connection.connect("conn1");
}
catch (error:ArgumentError)
{
    trace("Error! Server already exists\n");
}

NOTE

 

In earlier versions of ActionScript, the LocalConnection.connect() method returns a Boolean value if the connection name has already been used. In ActionScript 3.0, an error is generated if the name has already been used.

Connecting to the primary SWF file from a secondary SWF file requires that you create a new LocalConnection object in the sending LocalConnection object and then call the LocalConnection.send() method with the name of the connection and the name of the method to execute. For example, to connect to the LocalConnection object that you created earlier, you use the following code:

sendingConnection.send("conn1", "doQuit");

This code connects to an existing LocalConnection object with the connection name conn1 and invokes the doQuit() method in the remote SWF file. If you want to send parameters to the remote SWF file, you specify additional arguments after the method name in the send() method, as the following snippet shows:

sendingConnection.send("conn1", "doMessage", "Hello world");

Connecting to SWF documents in different domains

To allow communications only from specific domains, you call the allowDomain() or allowInsecureDomain() method of the LocalConnection class and pass a list of one or more domains that are allowed to access this LocalConnection object.

In earlier versions of ActionScript, LocalConnection.allowDomain() and LocalConnection.allowInsecureDomain() were callback methods that had to be implemented by developers and that had to return a Boolean value. In ActionScript 3.0, LocalConnection.allowDomain() and LocalConnection.allowInsecureDomain() are both built-in methods, which developers can call just like Security.allowDomain() and Security.allowInsecureDomain(), passing one or more names of domains to be allowed.

There are two special values that you can pass to the LocalConnection.allowDomain() and LocalConnection.allowInsecureDomain() methods: * and localhost. The asterisk value (*) allows access from all domains. The string localhost allows calls to the SWF file from SWF files that are locally installed.

Flash Player 8 introduced security restrictions on local SWF files. A SWF file that is allowed to access the Internet cannot also have access to the local file system. If you specify localhost, any local SWF file can access the SWF file. If the LocalConnection.send() method attempts to communicate with a SWF file from a security sandbox to which the calling code does not have access, a securityError event (SecurityErrorEvent.SECURITY_ERROR) is dispatched. To work around this error, you can specify the caller's domain in the receiver's LocalConnection.allowDomain() method.

If you implement communication only between SWF files in the same domain, you can specify a connectionName parameter that does not begin with an underscore (_) and does not specify a domain name (for example, myDomain:connectionName). Use the same string in the LocalConnection.connect(connectionName) command.

If you implement communication between SWF files in different domains, you specify a connectionName parameter that begins with an underscore. Specifying the underscore makes the SWF file with the receiving LocalConnection object more portable between domains. Here are the two possible cases:


Flash CS3