Packageflash.net
Classpublic class NetConnection
InheritanceNetConnection Inheritance EventDispatcher Inheritance Object

Language Version : ActionScript 3.0
Player Version : Flash Player 9

The NetConnection class lets you invoke commands on a remote application server, such as Adobe's Flash Media Server 2 or Adobe Flex, and to play streaming Flash Video (FLV) files from either an HTTP address or a local drive. Typically, you use NetConnection objects with NetStream objects.

When you use this class, consider the Flash Player security model:

For more information, see the following:

Some of the properties and methods in the NetStream class are intended for use primarily with a server, such as Flash Media Server or Flex. They may contain additional server-side functionality. For additional documentation, see the NetStream class in Flash Media Server documentation.

Note: This class was dynamic in ActionScript 2.0 but is now sealed. To write callback methods for this class, you can either extend the class and define the callback methods in your subclass, or you can use the client property to refer to an object and define the callback methods on that object.

View the examples

See also

client
NetStream


Public Properties
 PropertyDefined By
  client : Object
Indicates the object on which callback methods should be invoked.
NetConnection
  connected : Boolean
[read-only] Indicates whether Flash Player has connected to a server through a persistent RTMP connection (true) or not (false).
NetConnection
  connectedProxyType : String
[read-only] If a successful connection is made, indicates the method that was used to make it: a direct connection, the CONNECT method, or HTTP tunneling.
NetConnection
 Inheritedconstructor : Object
A reference to the class object or constructor function for a given object instance.
Object
  defaultObjectEncoding : uint
[static] The default object encoding (AMF version) for NetConnection objects created in the SWF file.
NetConnection
  objectEncoding : uint
The object encoding (AMF version) for this NetConnection instance.
NetConnection
 Inheritedprototype : Object
[static] A reference to the prototype object of a class or function object.
Object
  proxyType : String
Determines whether native SSL is used for RTMPS instead of HTTPS, and whether the CONNECT method of tunneling is used to connect through a proxy server.
NetConnection
  uri : String
[read-only] The URI of the application server that was passed to NetConnection.connect(), if connect was used to connect to a server.
NetConnection
  usingTLS : Boolean
[read-only] Indicates whether a secure connection was made using native Transport Layer Security (TLS) rather than HTTPS.
NetConnection
Public Methods
 MethodDefined By
  
Creates a NetConnection object that you can use with a NetStream object to invoke commands on a remote application server or to play back streaming video (FLV) files locally or from a server.
NetConnection
 Inherited
addEventListener(type:String, listener:Function, useCapture:Boolean = false, priority:int = 0, useWeakReference:Boolean = false):void
Registers an event listener object with an EventDispatcher object so that the listener receives notification of an event.
EventDispatcher
  
addHeader(operation:String, mustUnderstand:Boolean = false, param:Object = null):void
Adds a context header to the AMF packet structure.
NetConnection
  
call(command:String, responder:Responder, ... arguments):void
Invokes a command or method on the server running Flash Media Server, or on an application server, to which the application instance is connected.
NetConnection
  
Closes the connection that was opened locally or with the server and dispatches the netStatus event with a code property of NetConnection.Connect.Closed.
NetConnection
  
connect(command:String, ... arguments):void
Opens a connection to a server.
NetConnection
 Inherited
Dispatches an event into the event flow.
EventDispatcher
 Inherited
Checks whether the EventDispatcher object has any listeners registered for a specific type of event.
EventDispatcher
 Inherited
Indicates whether an object has a specified property defined.
Object
 Inherited
Indicates whether an instance of the Object class is in the prototype chain of the object specified as the parameter.
Object
 Inherited
Indicates whether the specified property exists and is enumerable.
Object
 Inherited
removeEventListener(type:String, listener:Function, useCapture:Boolean = false):void
Removes a listener from the EventDispatcher object.
EventDispatcher
 Inherited
Sets the availability of a dynamic property for loop operations.
Object
 Inherited
Returns the string representation of the specified object.
Object
 Inherited
Returns the primitive value of the specified object.
Object
 Inherited
Checks whether an event listener is registered with this EventDispatcher object or any of its ancestors for the specified event type.
EventDispatcher
Events
 Event Summary Defined By
 Inherited Dispatched when Flash Player gains operating system focus and becomes active.EventDispatcher
   Dispatched when an exception is thrown asynchronously — that is, from native asynchronous code.NetConnection
 Inherited Dispatched when Flash Player loses operating system focus and is becoming inactive.EventDispatcher
   Dispatched when an input or output error occurs that causes a network operation to fail.NetConnection
   Dispatched when a NetConnection object is reporting its status or error condition.NetConnection
   Dispatched if a call to NetConnection.call() attempts to connect to a server outside the caller's security sandbox.NetConnection
Property Detail
clientproperty
client:Object  [read-write]

Language Version : ActionScript 3.0
Player Version : Flash Player 9

Indicates the object on which callback methods should be invoked. The default is this NetConnection instance. If you set the client property to another object, callback methods will be invoked on that object.


Implementation
    public function get client():Object
    public function set client(value:Object):void

Throws
TypeError — The client property must be set to a non-null object.
connectedproperty 
connected:Boolean  [read-only]

Language Version : ActionScript 3.0
Player Version : Flash Player 9

Indicates whether Flash Player has connected to a server through a persistent RTMP connection (true) or not (false). When connected through HTTP, this property is always false. It is always true for AMF connections to application servers.


Implementation
    public function get connected():Boolean
connectedProxyTypeproperty 
connectedProxyType:String  [read-only]

Language Version : ActionScript 3.0
Player Version : Flash Player 9

If a successful connection is made, indicates the method that was used to make it: a direct connection, the CONNECT method, or HTTP tunneling. Possible values are "none", "HTTP", "HTTPS", and "CONNECT". This property is valid only when a NetConnection object is connected. This property is used in Flex applications and Flash Media Server applications. In Flash Player 9, this property is applicable only when RTMP, RTMPS, or RTMPT is used. The CONNECT method is applicable only to users who are connected to the network by a proxy server.

You can read this property to determine which method of connection was used. This property returns "none" if a direct connection was made, "HTTP" if HTTP tunneling was used, "HTTPS" if secure HTTPS tunneling was used, and "CONNECT" if the proxy CONNECT method was used.


Implementation
    public function get connectedProxyType():String

Throws
ArgumentError — An attempt was made to access this property when the NetConnection instance was not connected.
defaultObjectEncodingproperty 
defaultObjectEncoding:uint  [read-write]

Language Version : ActionScript 3.0
Player Version : Flash Player 9

The default object encoding (AMF version) for NetConnection objects created in the SWF file. When an object is written to or read from binary data, the defaultObjectEncoding property indicates which Action Message Format version should be used: the ActionScript 3.0 format or the ActionScript 1.0 and ActionScript 2.0 format.

By default, NetConnection.defaultObjectEncoding is set to use the ActionScript 3.0 format, AMF3. Changing NetConnection.defaultObjectEncoding does not affect existing NetConnection instances; it affects only instances that are created subsequently.

To set an object's encoding separately (rather than setting object encoding for the entire SWF file), set the objectEncoding property of the NetConnection object instead.

For more detailed information, see the description of the objectEncoding property.


Implementation
    public static function get defaultObjectEncoding():uint
    public function set defaultObjectEncoding(value:uint):void

See also

objectEncodingproperty 
objectEncoding:uint  [read-write]

Language Version : ActionScript 3.0
Player Version : Flash Player 9

The object encoding (AMF version) for this NetConnection instance. The default value of this property is the value of defaultObjectEncoding. Acceptable values are ObjectEncoding.AMF3 and ObjectEncoding.AMF0.

It's important to understand this property if your ActionScript 3.0 SWF file needs to communicate with servers released prior to Flash Player 9.

When an object is written to or read from binary data, the objectEncoding property indicates which Action Message Format version should be used: the ActionScript 3.0 format (ObjectEncoding.AMF3) or the ActionScript 1.0 and ActionScript 2.0 format (ObjectEncoding.AMF0). When you use NetConnection objects to connect to a server, three scenarios are possible:

Changing defaultObjectEncoding does not affect existing NetConnection instances; it affects only instances that are created subsequently.

Once the NetConnection instance is connected, its objectEncoding property is read-only.

If you use the wrong encoding to connect to a server, Flash Player dispatches the netStatus event. The NetStatusEvent.info property contains an information object with a code property value of NetConnection.Connect.Failed, and a description explaining that the object encoding is incorrect.


Implementation
    public function get objectEncoding():uint
    public function set objectEncoding(value:uint):void

Throws
ReferenceError — An attempt was made to set the value of the objectEncoding property while the NetConnection instance was connected.
 
ArgumentError — This property was set to a value other than ObjectEncoding.AMF0 or ObjectEncoding.AMF3.

See also

proxyTypeproperty 
proxyType:String  [read-write]

Language Version : ActionScript 3.0
Player Version : Flash Player 9

Determines whether native SSL is used for RTMPS instead of HTTPS, and whether the CONNECT method of tunneling is used to connect through a proxy server. Acceptable values are "none", "HTTP", "CONNECT", and "best". This property is used in Flex applications and Flash Media Server 2 applications.

In Flash Player 9, this property is applicable only when using RTMP, RTMPS, or RTMPT. The CONNECT method is applicable only to users who are connected to the network by a proxy server.

The proxyType property determines which fallback methods are tried if the initial connection attempt fails. You must set the proxyType property before calling the NetConnection.connect() method. This property determines whether to try to use native Transport Layer Security (TLS), and how to work with proxy servers that your application encounters when attempting to make a connection.

In Flash Player 9, the default value for this property is "none"; if you do not change this value, Flash Player uses HTTPS tunneling for RTMPS. If the property is set to "best", the optimal method of connecting is established, attempting the best method first and then falling back to other methods if they fail. For RTMPS connections, native SSL sockets are used by default, and a fallback to other methods is used if necessary. If the property is set to "HTTP" and a direct connection fails, the old method of HTTP tunneling is used. If the property is set to "CONNECT" and a direct connection fails, the CONNECT method of tunneling is used. If that fails, the connection will not fall back to HTTP tunneling.


Implementation
    public function get proxyType():String
    public function set proxyType(value:String):void
uriproperty 
uri:String  [read-only]

Language Version : ActionScript 3.0
Player Version : Flash Player 9

The URI of the application server that was passed to NetConnection.connect(), if connect was used to connect to a server. If NetConnection.connect() hasn't yet been called or if no URI was passed, this property is undefined.


Implementation
    public function get uri():String
usingTLSproperty 
usingTLS:Boolean  [read-only]

Language Version : ActionScript 3.0
Player Version : Flash Player 9

Indicates whether a secure connection was made using native Transport Layer Security (TLS) rather than HTTPS. This property is valid only when a NetConnection object is connected.


Implementation
    public function get usingTLS():Boolean

Throws
ArgumentError — An attempt was made to access this property when the NetConnection instance was not connected.
Constructor Detail
NetConnection()Constructor
public function NetConnection()

Language Version : ActionScript 3.0
Player Version : Flash Player 9

Creates a NetConnection object that you can use with a NetStream object to invoke commands on a remote application server or to play back streaming video (FLV) files locally. After creating the NetConnection object, use connect() to make the actual connection.

Playing external FLV files provides several advantages over embedding video in a Flash document, such as better performance, better memory management, and independent video and Flash frame rates.

If your ActionScript 3.0 SWF file needs to communicate with servers released prior to Flash Player 9, you might need to adjust the NetConnection object's objectEncoding property.

See also

Method Detail
addHeader()method
public function addHeader(operation:String, mustUnderstand:Boolean = false, param:Object = null):void

Language Version : ActionScript 3.0
Player Version : Flash Player 9

Adds a context header to the AMF packet structure. This header is sent with every future AMF packet. If you call NetConnection.addHeader() using the same name, the new header replaces the existing header, and the new header persists for the duration of the NetConnection object. You can remove a header by calling NetConnection.addHeader() with the name of the header to remove an undefined object. This method is relevant when used with a server, such as Flex or Flash Media Server.

Parameters

operation:String — Identifies the header and the ActionScript object data associated with it.
 
mustUnderstand:Boolean (default = false) — A value of true indicates that the server must understand and process this header before it handles any of the following headers or messages.
 
param:Object (default = null) — Any ActionScript object.

call()method 
public function call(command:String, responder:Responder, ... arguments):void

Language Version : ActionScript 3.0
Player Version : Flash Player 9

Invokes a command or method on the server running Flash Media Server, or on an application server, to which the application instance is connected. You must create a server-side function to pass to this method.

Parameters

command:String — A method specified in the form [objectPath/]method. For example, the someObject/doSomething command tells the remote server to invoke the clientObject.someObject.doSomething() method, with all the optional ... arguments parameters. If the object path is missing, clientObject.doSomething() is invoked on the remote server.
 
responder:Responder — An optional object that is used to handle return values from the server. The Responder object can have two defined methods to handle the returned result: result and status. If an error is returned as the result, status is invoked; otherwise, result is invoked. The Responder object can process errors related to specific operations, while the NetConnection object responds to errors related to the connection status.
 
... arguments — Optional arguments that can be of any ActionScript type, including a reference to another ActionScript object. These arguments are passed to the method specified in the command parameter when the method is executed on the remote application server.


Events
securityError:SecurityErrorEvent — A call attempted to communicate with a server outside the caller's security sandbox. You can avoid this problem by using a policy file on the server.
close()method 
public function close():void

Language Version : ActionScript 3.0
Player Version : Flash Player 9

Closes the connection that was opened locally or with the server and dispatches the netStatus event with a code property of NetConnection.Connect.Closed.

This method disconnects all NetStream objects running over this connection; any queued data that has not been sent is discarded. (To terminate streams without closing the connection, use NetStream.close().) If you call this method and then want to reconnect, you must recreate the NetStream object.

See also

connect()method 
public function connect(command:String, ... arguments):void

Language Version : ActionScript 3.0
Player Version : Flash Player 9

Opens a connection to a server. Through this connection, you can play back audio or video (FLV) files from the local file system, or you can invoke commands on a remote server.

When using this method, consider the Flash Player security model and the following security considerations:

For more information, see the following:

Parameters

command:String — Set this parameter to null if you are connecting to video without a server (that is, video on the local computer that is running the SWF file).

If you are connecting to a server, set this parameter to the URI of the application on the server that runs when the connection is made. Use the following format (items in brackets are optional):

protocol:[//host][:port]/appname/[instanceName]

If the SWF file is served from the same host where the server is installed, you can omit the host parameter. If you omit the instanceName parameter, Flash Player connects to the application's default instance (_definst_).

 
... arguments — Optional parameters of any type to be passed to the application specified in command. If the application is unable to process the parameters in the order in which they are received, netStatusEvent is dispatched with the code property set to NetConnection.Connect.Rejected.


Throws
ArgumentError — The URI passed to the command parameter is improperly formatted.
 
IOError — The connection failed. This might happen if you call connect() from within a netStatus event handler, which is not allowed.
 
SecurityError — Local untrusted SWF files cannot communicate with the Internet. You can avoid this problem by reclassifying this SWF file as local-with-networking or trusted.

See also

Event Detail
asyncError Event
Event Object Type: flash.events.AsyncErrorEvent
AsyncErrorEvent.type property = flash.events.AsyncErrorEvent.ASYNC_ERROR

Language Version : ActionScript 3.0
Player Version : Flash Player 9

Dispatched when an exception is thrown asynchronously — that is, from native asynchronous code.

The AsyncErrorEvent.ASYNC_ERROR constant defines the value of the type property of an asyncError event object.

This event has the following properties:

PropertyValue
bubblesfalse
cancelablefalse; there is no default behavior to cancel.
currentTargetThe object that is actively processing the Event object with an event listener.
targetThe object experiencing a network operation failure.
errorThe error that triggered the event.
ioError Event  
Event Object Type: flash.events.IOErrorEvent
IOErrorEvent.type property = flash.events.IOErrorEvent.IO_ERROR

Language Version : ActionScript 3.0
Player Version : Flash Player 9

Dispatched when an input or output error occurs that causes a network operation to fail.

Defines the value of the type property of an ioError event object.

This event has the following properties:

PropertyValue
bubblesfalse
cancelablefalse; there is no default behavior to cancel.
currentTargetThe object that is actively processing the Event object with an event listener.
targetThe network object experiencing the input/output error.
textText to be displayed as an error message.
netStatus Event  
Event Object Type: flash.events.NetStatusEvent
NetStatusEvent.type property = flash.events.NetStatusEvent.NET_STATUS

Language Version : ActionScript 3.0
Player Version : Flash Player 9

Dispatched when a NetConnection object is reporting its status or error condition. The netStatus event contains an info property, which is an information object that contains specific information about the event, such as whether a connection attempt succeeded or failed.

Defines the value of the type property of a netStatus event object.

This event has the following properties:

PropertyValue
bubblesfalse
cancelablefalse; there is no default behavior to cancel.
currentTargetThe object that is actively processing the Event object with an event listener.
infoAn object with properties that describe the object's status or error condition.
targetThe NetConnection or NetStream object reporting its status.

See also

securityError Event  
Event Object Type: flash.events.SecurityErrorEvent
SecurityErrorEvent.type property = flash.events.SecurityErrorEvent.SECURITY_ERROR

Language Version : ActionScript 3.0
Player Version : Flash Player 9

Dispatched if a call to NetConnection.call() attempts to connect to a server outside the caller's security sandbox.

The SecurityErrorEvent.SECURITY_ERROR constant defines the value of the type property of a securityError event object.

This event has the following properties:

PropertyValue
bubblesfalse
cancelablefalse; there is no default behavior to cancel.
currentTargetThe object that is actively processing the Event object with an event listener.
targetThe network object reporting the security error.
textText to be displayed as an error message.

See also

Examples How to use examples
NetConnectionExample.as

The following example uses a Video object with the NetConnection and NetStream classes to load and play an FLV file. To run this example, you need an FLV file whose name and location match the variable passed to videoURL; in this case, an FLV file called Video.flv that is in the same directory as the SWF file.

In this example, the code that creates the Video and NetStream objects and calls the Video.attachNetStream() and NetStream.play() methods is placed in a handler function. The handler is called only if the attempt to connect to the NetConnection object is successful; that is, when the netStatus event returns an info object with a code property that indicates success. It is recommended that you wait for a successful connection before you call NetStream.play().


package {
    import flash.display.Sprite;
    import flash.events.NetStatusEvent;
    import flash.events.SecurityErrorEvent;
    import flash.media.Video;
    import flash.net.NetConnection;
    import flash.net.NetStream;
    import flash.events.Event;

    public class NetConnectionExample extends Sprite {
        private var videoURL:String = "Video.flv";
        private var connection:NetConnection;
        private var stream:NetStream;

        public function NetConnectionExample() {
            connection = new NetConnection();
            connection.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler);
            connection.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
            connection.connect(null);
        }

        private function netStatusHandler(event:NetStatusEvent):void {
            switch (event.info.code) {
                case "NetConnection.Connect.Success":
                    connectStream();
                    break;
                case "NetStream.Play.StreamNotFound":
                    trace("Stream not found: " + videoURL);
                    break;
            }
        }

        private function securityErrorHandler(event:SecurityErrorEvent):void {
            trace("securityErrorHandler: " + event);
        }

        private function connectStream():void {
            var stream:NetStream = new NetStream(connection);
            stream.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler);
            stream.client = new CustomClient();
            var video:Video = new Video();
            video.attachNetStream(stream);
            stream.play(videoURL);
            addChild(video);
        }
    }
}

class CustomClient {
    public function onMetaData(info:Object):void {
        trace("metadata: duration=" + info.duration + " width=" + info.width + " height=" + info.height + " framerate=" + info.framerate);
    }
    public function onCuePoint(info:Object):void {
        trace("cuepoint: time=" + info.time + " name=" + info.name + " type=" + info.type);
    }
}




 

Send me an e-mail when comments are added to this page | Comment Report

Current page: http://livedocs.adobe.com/livecycle/es/sdkHelp/common/langref/flash/net/NetConnection.html