flash.netXMLSocket The XMLSocket class implements client sockets that let the Flash Player or AIR application communicate with a server computer identified by an IP address or domain name.flash.events:EventDispatcher The XMLSocket class implements client sockets that let the Flash Player or AIR application communicate with a server computer identified by an IP address or domain name. The XMLSocket class is useful for client-server applications that require low latency, such as real-time chat systems. A traditional HTTP-based chat solution frequently polls the server and downloads new messages using an HTTP request. In contrast, an XMLSocket chat solution maintains an open connection to the server, which lets the server immediately send incoming messages without a request from the client. To use the XMLSocket class, the server computer must run a daemon that understands the protocol used by the XMLSocket class. The protocol is described in the following list:
  • XML messages are sent over a full-duplex TCP/IP stream socket connection.
  • Each XML message is a complete XML document, terminated by a zero (0) byte.
  • An unlimited number of XML messages can be sent and received over a single XMLSocket connection.

Setting up a server to communicate with the XMLSocket object can be challenging. If your application does not require real-time interactivity, use the URLLoader class instead of the XMLSocket class.

To use the methods of the XMLSocket class, first use the constructor, new XMLSocket, to create an XMLSocket object.

SWF files in the local-with-filesystem sandbox may not use sockets.

Socket policy files on the target host specify the hosts from which SWF files can make socket connections, and the ports to which those connections can be made. The security requirements with regard to socket policy files have become more stringent in the last several releases of Flash Player. In all versions of Flash Player, Adobe recommends the use of a socket policy file; in some circumstances, a socket policy file is required. Therefore, if you are using XMLSocket objects, make sure that the target host provides a socket policy file if necessary.

The following list summarizes the requirements for socket policy files in different versions of Flash Player:

  • In Flash Player 9.0.124.0 and later, a socket policy file is required for any XMLSocket connection. That is, a socket policy file on the target host is required no matter what port you are connecting to, and is required even if you are connecting to a port on the same host that is serving the SWF file.
  • In Flash Player versions 9.0.115.0 and earlier, if you want to connect to a port number below 1024, or if you want to connect to a host other than the one serving the SWF file, a socket policy file on the target host is required.
  • In Flash Player 9.0.115.0, even if a socket policy file isn't required, a warning is displayed when using the Flash Debug Player if the target host doesn't serve a socket policy file.

However, in Adobe AIR, content in the application security sandbox (content installed with the AIR application) are not restricted by these security limitations.

For more information related to security, see the Flash Player Developer Center Topic: Security.

The following example uses the class XMLSocketExample class to send data using an XMLSocket and print information during XMLSocket events. This is accomplished using the following steps:
  1. The XMLSocketExample constructor creates a XMLSocket instance named socket and passes socket to ConfigureListeners() (described below) and then calls the connect() method of XMLSocket using the host name "localhost" and port number of 8080.
  2. The configureListeners() method is then called, which adds listeners for each of the supported XMLSocket events:
    • closeHandler(): listens for the close event, which is dispatched after the network connection has been closed.
    • connectHandler(): listens for the connect event, dispatched when the network connection has been established.
    • dataHandler(): listens for the data events, dispatched every time the XMLSocket receives new data.
    • progressHandler(): listens for the progress events, dispatched when a call to send() has been made and while the send is ongoing.
    • securityErrorHandler(): listens for securityError events, which would be dispatched if an attempt was made to access the XMLSocket with the wrong local playback security setting or using a port lower than 1024.
    • ioErrorHandler(): listens for ioError events, which would happen only if an operation to send or receive data failed.

Notes:

  • You need to compile the SWF file with "Local playback security" set to "Access network only".
  • You need a server running on your domain using port 8080 for this example to work.
  • If you are running Flash Player 9.0.124.0 or later, you need to place a socket policy file on your server that permits socket connections from your domain to port 8080. For information on serving socket policy files, see the Flash Player Developer Center Topic: Setting up a socket policy file server.

package { import flash.display.Sprite; import flash.events.*; import flash.net.XMLSocket; public class XMLSocketExample extends Sprite { private var hostName:String = "localhost"; private var port:uint = 8080; private var socket:XMLSocket; public function XMLSocketExample() { socket = new XMLSocket(); configureListeners(socket); if (hostName && port) { socket.connect(hostName, port); } } public function send(data:Object):void { socket.send(data); } private function configureListeners(dispatcher:IEventDispatcher):void { dispatcher.addEventListener(Event.CLOSE, closeHandler); dispatcher.addEventListener(Event.CONNECT, connectHandler); dispatcher.addEventListener(DataEvent.DATA, dataHandler); dispatcher.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler); dispatcher.addEventListener(ProgressEvent.PROGRESS, progressHandler); dispatcher.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler); } private function closeHandler(event:Event):void { trace("closeHandler: " + event); } private function connectHandler(event:Event):void { trace("connectHandler: " + event); } private function dataHandler(event:DataEvent):void { trace("dataHandler: " + event); } private function ioErrorHandler(event:IOErrorEvent):void { trace("ioErrorHandler: " + event); } private function progressHandler(event:ProgressEvent):void { trace("progressHandler loaded:" + event.bytesLoaded + " total: " + event.bytesTotal); } private function securityErrorHandler(event:SecurityErrorEvent):void { trace("securityErrorHandler: " + event); } } }
flash.net.URLLoader.load()flash.net.URLLoadersecurityError Dispatched if a call to the XMLSocket.connect() method attempts to connect either to a server outside the caller's security sandbox or to a port lower than 1024.flash.events.SecurityErrorEvent.SECURITY_ERRORflash.events.SecurityErrorEvent Dispatched if a call to the XMLSocket.connect() method attempts to connect either to a server outside the caller's security sandbox or to a port lower than 1024. XMLSocket.connect()ioError Dispatched when an input/output error occurs that causes a send or receive operation to fail.flash.events.IOErrorEvent.IO_ERRORflash.events.IOErrorEvent Dispatched when an input/output error occurs that causes a send or receive operation to fail. data Dispatched after raw data is sent or received.flash.events.DataEvent.DATAflash.events.DataEvent Dispatched after raw data is sent or received. connect Dispatched after a successful call to the XMLSocket.connect() method.flash.events.Event.CONNECTflash.events.Event Dispatched after a successful call to the XMLSocket.connect() method. close Dispatched when the server closes the socket connection.flash.events.Event.CLOSEflash.events.Event Dispatched when the server closes the socket connection. The close event is dispatched only when the server closes the connection; it is not dispatched when you call the XMLSocket.close() method. XMLSocket Creates a new XMLSocket object.hostStringnullA fully qualified DNS domain name or an IP address in the form .222.333.444. In Flash Player 9.0.115.0 and AIR 1.0 and later, you can specify IPv6 addresses, such as rtmp://[2001:db8:ccc3:ffff:0:444d:555e:666f]. You can also specify null to connect to the host server on which the SWF file resides. If the SWF file issuing this call is running in a web browser, host must be in the same domain as the SWF file. portint0The TCP port number on the target host used to establish a connection. In Flash Player 9.0.124.0 and later, the target host must serve a socket policy file specifying that socket connections are permitted from the host serving the SWF file to the specified port. In earlier versions of Flash Player, a socket policy file is required only if you want to connect to a port number below 1024, or if you want to connect to a host other than the one serving the SWF file. Creates a new XMLSocket object. If no parameters are specified, an initially disconnected socket is created. If parameters are specified, a connection is attempted to the specified host and port.

Note: It is strongly advised to use the constructor form without parameters, then add any event listeners, then call the connect method with host and port parameters. This sequence guarantees that all event listeners will work properly.

connect()
close Closes the connection specified by the XMLSocket object. Closes the connection specified by the XMLSocket object. The close event is dispatched only when the server closes the connection; it is not dispatched when you call the close() method. connect()connect Establishes a connection to the specified Internet host using the specified TCP port.Local untrusted files may not communicate with the Internet. Work around this limitation by reclassifying the file as local-with-networking or trusted. SecurityErrorSecurityErrorYou may not specify a socket port higher than 65535. SecurityErrorSecurityErrorhostStringA fully qualified DNS domain name or an IP address in the form 111.222.333.444. You can also specify null to connect to the host server on which the SWF file resides. If the calling file is a SWF file running in a web browser, host must be in the same domain as the file. portintThe TCP port number on the target host used to establish a connection. In Flash Player 9.0.124.0 and later, the target host must serve a socket policy file specifying that socket connections are permitted from the host serving the SWF file to the specified port. In earlier versions of Flash Player, a socket policy file is required only if you want to connect to a port number below 1024, or if you want to connect to a host other than the one serving the SWF file. Establishes a connection to the specified Internet host using the specified TCP port.

If you specify null for the host parameter, the host contacted is the one where the file calling XMLSocket.connect() resides. For example, if the calling file was downloaded from www.adobe.com, specifying null for the host parameter means you are connecting to www.adobe.com.

You can prevent a file from using this method by setting the allowNetworking parameter of the the object and embed tags in the HTML page that contains the SWF content.

For more information, see the Flash Player Developer Center Topic: Security.

flash.events.Event.CONNECTsecurityErrorflash.events:SecurityErrorEventA connect operation attempted to connect to a host outside the caller's security sandbox, or to a port that requires a socket policy file. Work around either problem by using a socket policy file on the target host. A connect operation attempted to connect to a host outside the caller's security sandbox, or to a port that requires a socket policy file.dataflash.events:DataEventDispatched when raw data has been received. Dispatched when raw data has been received.connectflash.events:EventDispatched when network connection has been established. Dispatched when network connection has been established.
send Converts the XML object or data specified in the object parameter to a string and transmits it to the server, followed by a zero (0) byte.The XMLSocket object is not connected to the server. IOErrorflash.errors:IOErrorobjectAn XML object or other data to transmit to the server. Converts the XML object or data specified in the object parameter to a string and transmits it to the server, followed by a zero (0) byte. If object is an XML object, the string is the XML textual representation of the XML object. The send operation is asynchronous; it returns immediately, but the data may be transmitted at a later time. The XMLSocket.send() method does not return a value indicating whether the data was successfully transmitted.

If you do not connect the XMLSocket object to the server using XMLSocket.connect()), the XMLSocket.send() operation fails.

connect()
connected Indicates whether this XMLSocket object is currently connected.Boolean Indicates whether this XMLSocket object is currently connected. You can also check whether the connection succeeded by registering for the connect event and ioError event. connectioErrortimeout Indicates the number of milliseconds to wait for a connection.int Indicates the number of milliseconds to wait for a connection.

If the connection doesn't succeed within the specified time, the connection fails. The default value is 20,000 (twenty seconds).

IPVersion The IPVersion class defines constants representing the different families of IP addresses.Object The IPVersion class defines constants representing the different families of IP addresses. IPV4 An Internet Protocol version 4 (IPv4) address.IPv4String An Internet Protocol version 4 (IPv4) address.

IPv4 addresses are expressed in ActionScript as a string in dot-decimal notation, such as: "192.0.2.0".

IPV6 An Internet Protocol version 6 (IPv6) address.IPv6String An Internet Protocol version 6 (IPv6) address.

IPv6 addresses are expressed in ActionScript as a string in hexadecimal-colon notation and enclosed in brackets, such as: "[2001:db8:ccc3:ffff:0:444d:555e:666f]".

Socket The Socket class enables code to establish Transport Control Protocol (TCP) socket connections for sending and receiving binary data.flash.utils:IDataInputflash.utils:IDataOutputflash.events:EventDispatcher The Socket class enables code to establish Transport Control Protocol (TCP) socket connections for sending and receiving binary data.

The Socket class is useful for working with servers that use binary protocols.

To use the methods of the Socket class, first use the constructor, new Socket, to create a Socket object.

A socket transmits and receives data asynchronously.

On some operating systems, flush() is called automatically between execution frames, but on other operating systems, such as Windows, the data is never sent unless you call flush() explicitly. To ensure your application behaves reliably across all operating systems, it is a good practice to call the flush() method after writing each message (or related group of data) to the socket.

In Adobe AIR, Socket objects are also created when a listening ServerSocket receives a connection from an external process. The Socket representing the connection is dispatched in a ServerSocketConnectEvent. Your application is responsible for maintaining a reference to this Socket object. If you don't, the Socket object is eligible for garbage collection and may be destroyed by the runtime without warning.

SWF content running in the local-with-filesystem security sandbox cannot use sockets.

Socket policy files on the target host specify the hosts from which SWF files can make socket connections, and the ports to which those connections can be made. The security requirements with regard to socket policy files have become more stringent in the last several releases of Flash Player. In all versions of Flash Player, Adobe recommends the use of a socket policy file; in some circumstances, a socket policy file is required. Therefore, if you are using Socket objects, make sure that the target host provides a socket policy file if necessary.

The following list summarizes the requirements for socket policy files in different versions of Flash Player:

  • In Flash Player 9.0.124.0 and later, a socket policy file is required for any socket connection. That is, a socket policy file on the target host is required no matter what port you are connecting to, and is required even if you are connecting to a port on the same host that is serving the SWF file.
  • In Flash Player versions 9.0.115.0 and earlier, if you want to connect to a port number below 1024, or if you want to connect to a host other than the one serving the SWF file, a socket policy file on the target host is required.
  • In Flash Player 9.0.115.0, even if a socket policy file isn't required, a warning is displayed when using the Flash Debug Player if the target host doesn't serve a socket policy file.
  • In AIR, a socket policy file is not required for content running in the application security sandbox. Socket policy files are required for any socket connection established by content running outside the AIR application security sandbox.

For more information related to security, see the Flash Player Developer Center Topic: Security

The following example reads from and writes to a socket and outputs information transmitted during socket events. Highlights of the example follow:
  1. The constructor creates a CustomSocket instance named socket and passes the host name localhost and port 80 as arguments. Since CustomSocket extends Socket, a call to super() calls Socket's constructor.
  2. The example then calls the configureListeners() method, which adds listeners for Socket events.
  3. Finally, the socket connect() method is called with localhost as the host name and 80 as the port number.

Note: To run the example, you need a server running on the same domain where the SWF resides (in the example, localhost) and listening on port 80.

package { import flash.display.Sprite; public class SocketExample extends Sprite { public function SocketExample() { var socket:CustomSocket = new CustomSocket("localhost", 80); } } } import flash.errors.*; import flash.events.*; import flash.net.Socket; class CustomSocket extends Socket { private var response:String; public function CustomSocket(host:String = null, port:uint = 0) { super(); configureListeners(); if (host && port) { super.connect(host, port); } } private function configureListeners():void { addEventListener(Event.CLOSE, closeHandler); addEventListener(Event.CONNECT, connectHandler); addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler); addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler); addEventListener(ProgressEvent.SOCKET_DATA, socketDataHandler); } private function writeln(str:String):void { str += "\n"; try { writeUTFBytes(str); } catch(e:IOError) { trace(e); } } private function sendRequest():void { trace("sendRequest"); response = ""; writeln("GET /"); flush(); } private function readResponse():void { var str:String = readUTFBytes(bytesAvailable); response += str; } private function closeHandler(event:Event):void { trace("closeHandler: " + event); trace(response.toString()); } private function connectHandler(event:Event):void { trace("connectHandler: " + event); sendRequest(); } private function ioErrorHandler(event:IOErrorEvent):void { trace("ioErrorHandler: " + event); } private function securityErrorHandler(event:SecurityErrorEvent):void { trace("securityErrorHandler: " + event); } private function socketDataHandler(event:ProgressEvent):void { trace("socketDataHandler: " + event); readResponse(); } }
ServerSocketDatagramSocketsecurityError Dispatched if a call to Socket.connect() attempts to connect to a server prohibited by the caller's security sandbox or to a port lower than 1024 and no socket policy file exists to permit such a connection.flash.events.SecurityErrorEvent.SECURITY_ERRORflash.events.SecurityErrorEventDispatched when a security error occurs. Dispatched if a call to Socket.connect() attempts to connect to a server prohibited by the caller's security sandbox or to a port lower than 1024 and no socket policy file exists to permit such a connection.

Note: In an AIR application, content running in the application security sandbox is permitted to connect to any server and port number without a socket policy file.

Socket.connect()
socketData Dispatched when a socket has received data.flash.events.ProgressEvent.SOCKET_DATAflash.events.ProgressEvent Dispatched when a socket has received data.

The data received by the socket remains in the socket until it is read. You do not have to read all the available data during the handler for this event.

Events of type socketData do not use the ProgressEvent.bytesTotal property.

ioError Dispatched when an input/output error occurs that causes a send or load operation to fail.flash.events.IOErrorEvent.IO_ERRORflash.events.IOErrorEvent Dispatched when an input/output error occurs that causes a send or load operation to fail. connect Dispatched when a network connection has been established.flash.events.Event.CONNECTflash.events.Event Dispatched when a network connection has been established. close Dispatched when the server closes the socket connection.flash.events.Event.CLOSEflash.events.Event Dispatched when the server closes the socket connection.

The close event is dispatched only when the server closes the connection; it is not dispatched when you call the Socket.close() method.

Socket Creates a new Socket object.This error occurs in SWF content for the following reasons:
  • Local-with-filesystem files cannot communicate with the Internet. You can work around this problem by reclassifying this SWF file as local-with-networking or trusted. This limitation is not set for AIR application content in the application security sandbox.
  • You cannot specify a socket port higher than 65535.
SecurityErrorSecurityError
hostStringnullA fully qualified DNS domain name or an IP address. IPv4 addresses are specified in dot-decimal notation, such as 192.0.2.0. In Flash Player 9.0.115.0 and AIR 1.0 and later, you can specify IPv6 addresses using hexadecimal-colon notation, such as 2001:db8:ccc3:ffff:0:444d:555e:666f. You can also specify null to connect to the host server on which the SWF file resides. If the SWF file issuing this call is running in a web browser, host must be in the domain from which the SWF file originated. portint0The TCP port number on the target host used to establish a connection. In Flash Player 9.0.124.0 and later, the target host must serve a socket policy file specifying that socket connections are permitted from the host serving the SWF file to the specified port. In earlier versions of Flash Player, a socket policy file is required only if you want to connect to a port number below 1024, or if you want to connect to a host other than the one serving the SWF file.
Creates a new Socket object. If no parameters are specified, an initially disconnected socket is created. If parameters are specified, a connection is attempted to the specified host and port.

Note: It is strongly advised to use the constructor form without parameters, then add any event listeners, then call the connect method with host and port parameters. This sequence guarantees that all event listeners will work properly.

connectflash.events:EventDispatched when a network connection has been established. Dispatched when a network connection has been established.ioErrorflash.events:IOErrorEventDispatched when an input/output error occurs that causes the connection to fail. Dispatched when an input/output error occurs that causes the connection to fail.securityErrorflash.events:SecurityErrorEvent Dispatched if a call to Socket.connect() attempts to connect either to a server that doesn't serve a socket policy file, or to a server whose policy file doesn't grant the calling host access to the specified port. For more information on policy files, see "Website controls (policy files)" in the ActionScript 3.0 Developer's Guide and the Flash Player Developer Center Topic: Security. This error occurs in SWF content. Dispatched if a call to Socket.connect() attempts to connect either to a server that doesn't serve a socket policy file, or to a server whose policy file doesn't grant the calling host access to the specified port.
close Closes the socket.The socket could not be closed, or the socket was not open. IOErrorflash.errors:IOError Closes the socket. You cannot read or write any data after the close() method has been called.

The close event is dispatched only when the server closes the connection; it is not dispatched when you call the close() method.

You can reuse the Socket object by calling the connect() method on it again.

connect Connects the socket to the specified host and port.No host was specified and the connection failed. IOErrorflash.errors:IOErrorThis error occurs in SWF content for the following reasons:
  • Local untrusted SWF files may not communicate with the Internet. You can work around this limitation by reclassifying the file as local-with-networking or as trusted.
  • You cannot specify a socket port higher than 65535.
  • In the HTML page that contains the SWF content, the allowNetworking parameter of the object and embed tags is set to "none".
SecurityErrorSecurityError
hostStringThe name or IP address of the host to connect to. If no host is specified, the host that is contacted is the host where the calling file resides. If you do not specify a host, use an event listener to determine whether the connection was successful. portintThe port number to connect to.
Connects the socket to the specified host and port.

If the connection fails immediately, either an event is dispatched or an exception is thrown: an error event is dispatched if a host was specified, and an exception is thrown if no host was specified. Otherwise, the status of the connection is reported by an event. If the socket is already connected, the existing connection is closed first.

connectflash.events:EventDispatched when a network connection has been established. Dispatched when a network connection has been established.ioErrorflash.events:IOErrorEventDispatched if a host is specified and an input/output error occurs that causes the connection to fail. Dispatched if a host is specified and an input/output error occurs that causes the connection to fail.securityErrorflash.events:SecurityErrorEventDispatched if a call to Socket.connect() attempts to connect either to a server that doesn't serve a socket policy file, or to a server whose policy file doesn't grant the calling host access to the specified port. For more information on policy files, see "Website controls (policy files)" in the ActionScript 3.0 Developer's Guide and the Flash Player Developer Center Topic: Security. Dispatched if a call to Socket.connect() attempts to connect either to a server that doesn't serve a socket policy file, or to a server whose policy file doesn't grant the calling host access to the specified port.
flush Flushes any accumulated data in the socket's output buffer.An I/O error occurred on the socket, or the socket is not open. IOErrorflash.errors:IOError Flushes any accumulated data in the socket's output buffer.

On some operating systems, flush() is called automatically between execution frames, but on other operating systems, such as Windows, the data is never sent unless you call flush() explicitly. To ensure your application behaves reliably across all operating systems, it is a good practice to call the flush() method after writing each message (or related group of data) to the socket.

readBoolean Reads a Boolean value from the socket.There is insufficient data available to read. EOFErrorflash.errors:EOFErrorAn I/O error occurred on the socket, or the socket is not open. IOErrorflash.errors:IOErrorA value of true if the byte read is nonzero, otherwise false. Boolean Reads a Boolean value from the socket. After reading a single byte, the method returns true if the byte is nonzero, and false otherwise. readByte Reads a signed byte from the socket.There is insufficient data available to read. EOFErrorflash.errors:EOFErrorAn I/O error occurred on the socket, or the socket is not open. IOErrorflash.errors:IOErrorA value from -128 to 127. int Reads a signed byte from the socket. readBytes Reads the number of data bytes specified by the length parameter from the socket.There is insufficient data available to read. EOFErrorflash.errors:EOFErrorAn I/O error occurred on the socket, or the socket is not open. IOErrorflash.errors:IOErrorbytesflash.utils:ByteArrayThe ByteArray object to read data into. offsetuint0The offset at which data reading should begin in the byte array. lengthuint0The number of bytes to read. The default value of 0 causes all available data to be read. Reads the number of data bytes specified by the length parameter from the socket. The bytes are read into the specified byte array, starting at the position indicated by offset. readDouble Reads an IEEE 754 double-precision floating-point number from the socket.There is insufficient data available to read. EOFErrorflash.errors:EOFErrorAn I/O error occurred on the socket, or the socket is not open. IOErrorflash.errors:IOErrorAn IEEE 754 double-precision floating-point number. Number Reads an IEEE 754 double-precision floating-point number from the socket. readFloat Reads an IEEE 754 single-precision floating-point number from the socket.There is insufficient data available to read. EOFErrorflash.errors:EOFErrorAn I/O error occurred on the socket, or the socket is not open. IOErrorflash.errors:IOErrorAn IEEE 754 single-precision floating-point number. Number Reads an IEEE 754 single-precision floating-point number from the socket. readInt Reads a signed 32-bit integer from the socket.There is insufficient data available to read. EOFErrorflash.errors:EOFErrorAn I/O error occurred on the socket, or the socket is not open. IOErrorflash.errors:IOErrorA value from -2147483648 to 2147483647. int Reads a signed 32-bit integer from the socket. readMultiByte Reads a multibyte string from the byte stream, using the specified character set.There is insufficient data available to read. EOFErrorflash.errors:EOFErrorA UTF-8 encoded string. StringlengthuintThe number of bytes from the byte stream to read. charSetStringThe string denoting the character set to use to interpret the bytes. Possible character set strings include "shift_jis", "CN-GB", and "iso-8859-1". For a complete list, see Supported Character Sets.

Note: If the value for the charSet parameter is not recognized by the current system, then the application uses the system's default code page as the character set. For example, a value for the charSet parameter, as in myTest.readMultiByte(22, "iso-8859-01") that uses 01 instead of 1 might work on your development machine, but not on another machine. On the other machine, the application will use the system's default code page.

Reads a multibyte string from the byte stream, using the specified character set.
readObject Reads an object from the socket, encoded in AMF serialized format.There is insufficient data available to read. EOFErrorflash.errors:EOFErrorAn I/O error occurred on the socket, or the socket is not open. IOErrorflash.errors:IOErrorThe deserialized object Reads an object from the socket, encoded in AMF serialized format. ObjectEncodingflash.net.registerClassAlias()readShort Reads a signed 16-bit integer from the socket.There is insufficient data available to read. EOFErrorflash.errors:EOFErrorAn I/O error occurred on the socket, or the socket is not open. IOErrorflash.errors:IOErrorA value from -32768 to 32767. int Reads a signed 16-bit integer from the socket. readUTFBytes Reads the number of UTF-8 data bytes specified by the length parameter from the socket, and returns a string.There is insufficient data available to read. EOFErrorflash.errors:EOFErrorAn I/O error occurred on the socket, or the socket is not open. IOErrorflash.errors:IOErrorA UTF-8 string. StringlengthuintThe number of bytes to read. Reads the number of UTF-8 data bytes specified by the length parameter from the socket, and returns a string. readUTF Reads a UTF-8 string from the socket.There is insufficient data available to read. EOFErrorflash.errors:EOFErrorAn I/O error occurred on the socket, or the socket is not open. IOErrorflash.errors:IOErrorA UTF-8 string. String Reads a UTF-8 string from the socket. The string is assumed to be prefixed with an unsigned short integer that indicates the length in bytes. readUnsignedByte Reads an unsigned byte from the socket.There is insufficient data available to read. EOFErrorflash.errors:EOFErrorAn I/O error occurred on the socket, or the socket is not open. IOErrorflash.errors:IOErrorA value from 0 to 255. uint Reads an unsigned byte from the socket. readUnsignedInt Reads an unsigned 32-bit integer from the socket.There is insufficient data available to read. EOFErrorflash.errors:EOFErrorAn I/O error occurred on the socket, or the socket is not open. IOErrorflash.errors:IOErrorA value from 0 to 4294967295. uint Reads an unsigned 32-bit integer from the socket. readUnsignedShort Reads an unsigned 16-bit integer from the socket.There is insufficient data available to read. EOFErrorflash.errors:EOFErrorAn I/O error occurred on the socket, or the socket is not open. IOErrorflash.errors:IOErrorA value from 0 to 65535. uint Reads an unsigned 16-bit integer from the socket. writeBoolean Writes a Boolean value to the socket.An I/O error occurred on the socket, or the socket is not open. IOErrorflash.errors:IOErrorvalueBooleanThe value to write to the socket: 1 (true) or 0 (false). Writes a Boolean value to the socket. This method writes a single byte, with either a value of 1 (true) or 0 (false). flush()writeByte Writes a byte to the socket.An I/O error occurred on the socket, or the socket is not open. IOErrorflash.errors:IOErrorvalueintThe value to write to the socket. The low 8 bits of the value are used; the high 24 bits are ignored. Writes a byte to the socket. flush()writeBytes Writes a sequence of bytes from the specified byte array.An I/O error occurred on the socket, or the socket is not open. IOErrorflash.errors:IOErrorIf offset is greater than the length of the ByteArray specified in bytes or if the amount of data specified to be written by offset plus length exceeds the data available. RangeErrorRangeErrorbytesflash.utils:ByteArrayThe ByteArray object to write data from. offsetuint0The zero-based offset into the bytes ByteArray object at which data writing should begin. lengthuint0The number of bytes to write. The default value of 0 causes the entire buffer to be written, starting at the value specified by the offset parameter. Writes a sequence of bytes from the specified byte array. The write operation starts at the position specified by offset.

If you omit the length parameter the default length of 0 causes the method to write the entire buffer starting at offset.

If you also omit the offset parameter, the entire buffer is written.

flush()
writeDouble Writes an IEEE 754 double-precision floating-point number to the socket.An I/O error occurred on the socket, or the socket is not open. IOErrorflash.errors:IOErrorvalueNumberThe value to write to the socket. Writes an IEEE 754 double-precision floating-point number to the socket. flush()writeFloat Writes an IEEE 754 single-precision floating-point number to the socket.An I/O error occurred on the socket, or the socket is not open. IOErrorflash.errors:IOErrorvalueNumberThe value to write to the socket. Writes an IEEE 754 single-precision floating-point number to the socket. flush()writeInt Writes a 32-bit signed integer to the socket.An I/O error occurred on the socket, or the socket is not open. IOErrorflash.errors:IOErrorvalueintThe value to write to the socket. Writes a 32-bit signed integer to the socket. flush()writeMultiByte Writes a multibyte string from the byte stream, using the specified character set.valueStringThe string value to be written. charSetStringThe string denoting the character set to use to interpret the bytes. Possible character set strings include "shift_jis", "CN-GB", and "iso-8859-1". For a complete list, see Supported Character Sets. Writes a multibyte string from the byte stream, using the specified character set. flush()writeObject Write an object to the socket in AMF serialized format.An I/O error occurred on the socket, or the socket is not open. IOErrorflash.errors:IOErrorobjectThe object to be serialized. Write an object to the socket in AMF serialized format. flush()ObjectEncodingflash.net.registerClassAlias()writeShort Writes a 16-bit integer to the socket.An I/O error occurred on the socket, or the socket is not open. IOErrorflash.errors:IOErrorvalueintThe value to write to the socket. Writes a 16-bit integer to the socket. The bytes written are as follows:
(v >> 8) & 0xff v & 0xff

The low 16 bits of the parameter are used; the high 16 bits are ignored.

flush()
writeUTFBytes Writes a UTF-8 string to the socket.An I/O error occurred on the socket, or the socket is not open. IOErrorflash.errors:IOErrorvalueStringThe string to write to the socket. Writes a UTF-8 string to the socket. flush()writeUTF Writes the following data to the socket: a 16-bit unsigned integer, which indicates the length of the specified UTF-8 string in bytes, followed by the string itself.The length is larger than 65535. RangeErrorRangeErrorAn I/O error occurred on the socket, or the socket is not open. IOErrorflash.errors:IOErrorvalueStringThe string to write to the socket. Writes the following data to the socket: a 16-bit unsigned integer, which indicates the length of the specified UTF-8 string in bytes, followed by the string itself.

Before writing the string, the method calculates the number of bytes that are needed to represent all characters of the string.

flush()
writeUnsignedInt Writes a 32-bit unsigned integer to the socket.An I/O error occurred on the socket, or the socket is not open. IOErrorflash.errors:IOErrorvalueuintThe value to write to the socket. Writes a 32-bit unsigned integer to the socket. flush()bytesAvailable The number of bytes of data available for reading in the input buffer.uint The number of bytes of data available for reading in the input buffer.

Your code must access bytesAvailable to ensure that sufficient data is available before trying to read it with one of the read methods.

connected Indicates whether this Socket object is currently connected.Boolean Indicates whether this Socket object is currently connected. A call to this property returns a value of true if the socket is currently connected, or false otherwise. endian Indicates the byte order for the data.StringEndian.BIG_ENDIAN Indicates the byte order for the data. Possible values are constants from the flash.utils.Endian class, Endian.BIG_ENDIAN or Endian.LITTLE_ENDIAN. flash.utils.EndianlocalAddress The IP address this socket is bound to on the local machine.String The IP address this socket is bound to on the local machine. bind()localPort The port this socket is bound to on the local machine.int The port this socket is bound to on the local machine. bind()objectEncoding Controls the version of AMF used when writing or reading an object.uint Controls the version of AMF used when writing or reading an object. ObjectEncoding classreadObject()writeObject()remoteAddress The IP address of the remote machine to which this socket is connected.String The IP address of the remote machine to which this socket is connected.

You can use this property to determine the IP address of a client socket dispatched in a ServerSocketConnectEvent by a ServerSocket object. Use the DNSResolver class to convert an IP address to a domain name, if desired.

connect()ServerSocketServerSocketConnectEventDNSResolver
remotePort The port on the remote machine to which this socket is connected.int The port on the remote machine to which this socket is connected.

You can use this property to determine the port number of a client socket dispatched in a ServerSocketConnectEvent by a ServerSocket object.

connect()ServerSocketServerSocketConnectEvent
timeout Indicates the number of milliseconds to wait for a connection.uint Indicates the number of milliseconds to wait for a connection.

If the connection doesn't succeed within the specified time, the connection fails. The default value is 20,000 (twenty seconds).

ObjectEncoding The ObjectEncoding class is used in defining serialization settings in classes that serialize objects (such as FileStream, NetStream, NetConnection, SharedObject, and ByteArray) to work with prior versions of ActionScript.Object The ObjectEncoding class is used in defining serialization settings in classes that serialize objects (such as FileStream, NetStream, NetConnection, SharedObject, and ByteArray) to work with prior versions of ActionScript.

Object encoding controls how objects are represented in Action Message Format (AMF). Flash Player uses AMF to enable efficient communication between an application and a remote server. AMF encodes remote procedure calls into a compact binary representation that can be transferred over HTTP/HTTPS or the RTMP/RTMPS protocol used by Flash Media Server. Objects and data values are serialized into this binary format, which is generally more compact than other representations, such as XML.

Adobe AIR and Flash Player 9 can serialize in two different formats: AMF3 and AMF0. AMF3, the default serialization developed for ActionScript 3.0, provides various advantages over AMF0, which is used for ActionScript 1.0 and 2.0. AMF3 sends data over the network more efficiently than AMF0. AMF3 supports sending int and uint objects as integers and supports data types that are available only in ActionScript 3.0, such as ByteArray, XML, and IExternalizable. It is available only in ActionScript 3.0 and with servers that use AMF3 encoding, such as Flex 2.

The ByteArray, FileStream, NetConnection, NetStream, SharedObject, Socket, and URLStream classes contain an objectEncoding property that is assigned a constant from the ObjectEncoding class. The behavior of the objectEncoding property differs depending on the object; each class's objectEncoding property description explains the behavior more thoroughly.

AMF0 Specifies that objects are serialized using the Action Message Format for ActionScript 1.0 and 2.0.0uint Specifies that objects are serialized using the Action Message Format for ActionScript 1.0 and 2.0. AMF3 Specifies that objects are serialized using the Action Message Format for ActionScript 3.0.3uint Specifies that objects are serialized using the Action Message Format for ActionScript 3.0. DEFAULT Specifies the default (latest) format for the current runtime (either Flash Player or AIR).3uint Specifies the default (latest) format for the current runtime (either Flash Player or AIR). Because object encoding control is only available in Flash Player 9 and later and Adobe AIR, the earliest format used will be the Action Message Format for ActionScript 3.0.

For example, if an object has the objectEncoding property set to ObjectEncoding.DEFAULT, AMF3 encoding is used. If, in the future, a later version of Flash Player or Adobe AIR introduces a new AMF version and you republish your content, the application will use that new AMF version. You can use this constant only if you're not concerned at all about interoperability with previous versions.

dynamicPropertyWriter Allows greater control over the serialization of dynamic properties of dynamic objects.flash.net:IDynamicPropertyWriter Allows greater control over the serialization of dynamic properties of dynamic objects. When this property is set to null, the default value, dynamic properties are serialized using native code, which writes all dynamic properties excluding those whose value is a function.

This value is called only for properties of a dynamic object (objects declared within a dynamic class) or for objects declared using the new operator.

You can use this property to exclude properties of dynamic objects from serialization; to write values to properties of dynamic objects; or to create new properties for dynamic objects. To do so, set this property to an object that implements the IDynamicPropertyWriter interface. For more information, see the IDynamicPropertyWriter interface.

IDynamicPropertyWriter
NetStreamAppendBytesAction The NetStreamAppendBytesAction class is an enumeration of the constants you can pass to the NetStream.appendBytesAction() method.Object The NetStreamAppendBytesAction class is an enumeration of the constants you can pass to the NetStream.appendBytesAction() method.

Two of the constants indicate a timescale discontinuity. Every FLV tag has a timestamp indicating its position in the timescale. Timestamps are used to synchronize video, audio, and script data playback. Timestamps for FLV tags of the same type (video, audio, script data) must not decrease as the FLV progresses.

flash.net.NetStream.appendBytesAction()flash.net.NetStream.appendBytes()END_SEQUENCE Indicates that the media stream data is complete.endSequenceString Indicates that the media stream data is complete. For some codecs, such as H.264, the byte parser waits for the buffer to fill to a certain point before beginning playback. Pass END_SEQUENCE to tell the byte parser to begin playback immediately. RESET_BEGIN Indicates a timescale discontinuity.resetBeginString Indicates a timescale discontinuity. Flushes the FIFO (composed of an incomplete FLV tag) and resets the timescale to begin at the timestamp of the next appended message. On the next call to appendBytes(), the byte parser expects a file header and starts at the beginning of a file. RESET_SEEK Indicates a timescale discontinuity.resetSeekString Indicates a timescale discontinuity. Flushes the FIFO (composed of an incomplete FLV tag) and resets the timescale to begin at the timestamp of the next appended message. On the next call to appendBytes(), the byte parser expects the beginning of an FLV tag, as though you’ve just done a seek to a location in the same FLV, on a tag boundary.
NetGroupReplicationStrategy The NetGroupReplicationStrategy class is an enumeration of constant values used in setting the replicationStrategy property of the NetGroup class.An enumeration of constant values used in setting the replicationStrategy property of the NetGroup class. Object The NetGroupReplicationStrategy class is an enumeration of constant values used in setting the replicationStrategy property of the NetGroup class. flash.net.NetGroup.addWantObjects()flash.net.NetGroup.replicationStrategyLOWEST_FIRST Specifies that when fetching objects from a neighbor to satisfy a want, the objects with the lowest index numbers are requested first.lowestFirstString Specifies that when fetching objects from a neighbor to satisfy a want, the objects with the lowest index numbers are requested first. flash.net.NetGroup.addWantObjects()RAREST_FIRST Specifies that when fetching objects from a neighbor to satisfy a want, the objects with the fewest replicas among all the neighbors are requested first.rarestFirstString Specifies that when fetching objects from a neighbor to satisfy a want, the objects with the fewest replicas among all the neighbors are requested first. NetGroup.addWantObjects()URLLoader The URLLoader class downloads data from a URL as text, binary data, or URL-encoded variables.flash.events:EventDispatcher The URLLoader class downloads data from a URL as text, binary data, or URL-encoded variables. It is useful for downloading text files, XML, or other information to be used in a dynamic, data-driven application.

A URLLoader object downloads all of the data from a URL before making it available to code in the applications. It sends out notifications about the progress of the download, which you can monitor through the bytesLoaded and bytesTotal properties, as well as through dispatched events.

When loading very large video files, such as FLV's, out-of-memory errors may occur.

When you use this class in Flash Player and in AIR application content in security sandboxes other than then application security sandbox, consider the following security model:

  • A SWF file in the local-with-filesystem sandbox may not load data from, or provide data to, a resource that is in the network sandbox.
  • By default, the calling SWF file and the URL you load must be in exactly the same domain. For example, a SWF file at www.adobe.com can load data only from sources that are also at www.adobe.com. To load data from a different domain, place a URL policy file on the server hosting the data.

For more information related to security, see the Flash Player Developer Center Topic: Security.

The following example loads and displays the data found in a local text file. It also traces event handling information.

Note: To run this example, put a file named urlLoaderExample.txt in the same directory as your SWF file. That file should only contain the following line of text: answer=42&question=unknown

The example code does the following:

  1. The constructor function creates a URLLoader instance named loader and a URLRequest instance named request, which contains the location and name of the file to be loaded.
  2. The loader object is passed to the configureListeners() method, which adds listeners for each of the supported URLLoader events.
  3. The request object is then passed to loader.load(), which loads the text file.
  4. When the URLLoader has finished loading the text file the Event.COMPLETE event fires, triggering the completeHandler() method. The completeHandler() method creates a URLVariables object from the text loaded from the file. The URLVariables object converts URL-encoded name/value pairs into ActionScript properties to make it easier to manipulate the loaded data.
package { import flash.display.Sprite; import flash.events.*; import flash.net.*; public class URLLoaderExample extends Sprite { public function URLLoaderExample() { var loader:URLLoader = new URLLoader(); configureListeners(loader); var request:URLRequest = new URLRequest("urlLoaderExample.txt"); try { loader.load(request); } catch (error:Error) { trace("Unable to load requested document."); } } private function configureListeners(dispatcher:IEventDispatcher):void { dispatcher.addEventListener(Event.COMPLETE, completeHandler); dispatcher.addEventListener(Event.OPEN, openHandler); dispatcher.addEventListener(ProgressEvent.PROGRESS, progressHandler); dispatcher.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler); dispatcher.addEventListener(HTTPStatusEvent.HTTP_STATUS, httpStatusHandler); dispatcher.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler); } private function completeHandler(event:Event):void { var loader:URLLoader = URLLoader(event.target); trace("completeHandler: " + loader.data); var vars:URLVariables = new URLVariables(loader.data); trace("The answer is " + vars.answer); } private function openHandler(event:Event):void { trace("openHandler: " + event); } private function progressHandler(event:ProgressEvent):void { trace("progressHandler loaded:" + event.bytesLoaded + " total: " + event.bytesTotal); } private function securityErrorHandler(event:SecurityErrorEvent):void { trace("securityErrorHandler: " + event); } private function httpStatusHandler(event:HTTPStatusEvent):void { trace("httpStatusHandler: " + event); } private function ioErrorHandler(event:IOErrorEvent):void { trace("ioErrorHandler: " + event); } } }
URLRequestURLVariablesURLStreamhttpResponseStatus Dispatched if a call to the load() method attempts to access data over HTTP, and Adobe AIR is able to detect and return the status code for the request.flash.events.HTTPStatusEvent.HTTP_RESPONSE_STATUSflash.events.HTTPStatusEvent Dispatched if a call to the load() method attempts to access data over HTTP, and Adobe AIR is able to detect and return the status code for the request. load()httpStatus Dispatched if a call to URLLoader.load() attempts to access data over HTTP.flash.events.HTTPStatusEvent.HTTP_STATUSflash.events.HTTPStatusEvent Dispatched if a call to URLLoader.load() attempts to access data over HTTP. For content running in Flash Player, this event is only dispatched if the current Flash Player environment is able to detect and return the status code for the request. (Some browser environments may not be able to provide this information.) Note that the httpStatus event (if any) is sent before (and in addition to) any complete or error event. URLLoader.load()securityError Dispatched if a call to URLLoader.load() attempts to load data from a server outside the security sandbox.flash.events.SecurityErrorEvent.SECURITY_ERRORflash.events.SecurityErrorEvent Dispatched if a call to URLLoader.load() attempts to load data from a server outside the security sandbox. Also dispatched if a call to URLLoader.load() attempts to load a SWZ file and the certificate is invalid or the digest string does not match the component. URLLoader.load()ioError Dispatched if a call to URLLoader.load() results in a fatal error that terminates the download.flash.events.IOErrorEvent.IO_ERRORflash.events.IOErrorEvent Dispatched if a call to URLLoader.load() results in a fatal error that terminates the download. URLLoader.load()progress Dispatched when data is received as the download operation progresses.flash.events.ProgressEvent.PROGRESSflash.events.ProgressEvent Dispatched when data is received as the download operation progresses.

Note that with a URLLoader object, it is not possible to access the data until it has been received completely. So, the progress event only serves as a notification of how far the download has progressed. To access the data before it's entirely downloaded, use a URLStream object.

URLLoader.load()
complete Dispatched after all the received data is decoded and placed in the data property of the URLLoader object.flash.events.Event.COMPLETEflash.events.Event Dispatched after all the received data is decoded and placed in the data property of the URLLoader object. The received data may be accessed once this event has been dispatched. URLLoader.load()open Dispatched when the download operation commences following a call to the URLLoader.load() method.flash.events.Event.OPENflash.events.EventDispatched when the download operation begins. Dispatched when the download operation commences following a call to the URLLoader.load() method. URLLoader.load()URLLoader Creates a URLLoader object.requestflash.net:URLRequestnullA URLRequest object specifying the URL to download. If this parameter is omitted, no load operation begins. If specified, the load operation begins immediately (see the load entry for more information). Creates a URLLoader object. URLLoader.load()addEventListener Registers an event listener object with an EventDispatcher object so that the listener receives notification of an event.typeStringThe type of event. listenerFunctionThe listener function that processes the event. This function must accept an Event object as its only parameter and must return nothing, as this example shows: function(evt:Event):void

The function can have any name.

useCaptureBooleanfalse Determines whether the listener works in the capture phase or the target and bubbling phases. If useCapture is set to true, the listener processes the event only during the capture phase and not in the target or bubbling phase. If useCapture is false, the listener processes the event only during the target or bubbling phase. To listen for the event in all three phases, call addEventListener twice, once with useCapture set to true, then again with useCapture set to false. priorityint0The priority level of the event listener. The priority is designated by a signed 32-bit integer. The higher the number, the higher the priority. All listeners with priority n are processed before listeners of priority n-1. If two or more listeners share the same priority, they are processed in the order in which they were added. The default priority is 0. useWeakReferenceBooleanfalseDetermines whether the reference to the listener is strong or weak. A strong reference (the default) prevents your listener from being garbage-collected. A weak reference does not.

Class-level member functions are not subject to garbage collection, so you can set useWeakReference to true for class-level member functions without subjecting them to garbage collection. If you set useWeakReference to true for a listener that is a nested inner function, the function will be garbage-collected and no longer persistent. If you create references to the inner function (save it in another variable) then it is not garbage-collected and stays persistent.

Registers an event listener object with an EventDispatcher object so that the listener receives notification of an event. You can register event listeners on all nodes in the display list for a specific type of event, phase, and priority.

After you successfully register an event listener, you cannot change its priority through additional calls to addEventListener(). To change a listener's priority, you must first call removeListener(). Then you can register the listener again with the new priority level.

Keep in mind that after the listener is registered, subsequent calls to addEventListener() with a different type or useCapture value result in the creation of a separate listener registration. For example, if you first register a listener with useCapture set to true, it listens only during the capture phase. If you call addEventListener() again using the same listener object, but with useCapture set to false, you have two separate listeners: one that listens during the capture phase and another that listens during the target and bubbling phases.

You cannot register an event listener for only the target phase or the bubbling phase. Those phases are coupled during registration because bubbling applies only to the ancestors of the target node.

If you no longer need an event listener, remove it by calling removeEventListener(), or memory problems could result. Event listeners are not automatically removed from memory because the garbage collector does not remove the listener as long as the dispatching object exists (unless the useWeakReference parameter is set to true).

Copying an EventDispatcher instance does not copy the event listeners attached to it. (If your newly created node needs an event listener, you must attach the listener after creating the node.) However, if you move an EventDispatcher instance, the event listeners attached to it move along with it.

If the event listener is being registered on a node while an event is being processed on this node, the event listener is not triggered during the current phase but can be triggered during a later phase in the event flow, such as the bubbling phase.

If an event listener is removed from a node while an event is being processed on the node, it is still triggered by the current actions. After it is removed, the event listener is never invoked again (unless registered again for future processing).

close Closes the load operation in progress. Closes the load operation in progress. Any load operation in progress is immediately terminated. If no URL is currently being streamed, an invalid stream error is thrown. load Sends and loads data from the specified URL.URLRequest.requestHeader objects may not contain certain prohibited HTTP request headers. For more information, see the URLRequestHeader class description. ArgumentErrorArgumentErrorThis error can occur for the following reasons: 1) Flash Player or AIR cannot convert the URLRequest.data parameter from UTF8 to MBCS. This error is applicable if the URLRequest object passed to load() is set to perform a GET operation and if System.useCodePage is set to true. 2) Flash Player or AIR cannot allocate memory for the POST data. This error is applicable if the URLRequest object passed to load is set to perform a POST operation. MemoryErrorflash.errors:MemoryErrorLocal untrusted files may not communicate with the Internet. This may be worked around by reclassifying this file as local-with-networking or trusted. SecurityErrorSecurityErrorYou are trying to connect to a commonly reserved port. For a complete list of blocked ports, see "Restricting Networking APIs" in the ActionScript 3.0 Developer's Guide. SecurityErrorSecurityErrorThe value of the request parameter or the URLRequest.url property of the URLRequest object passed are null. TypeErrorTypeErrorrequestflash.net:URLRequestA URLRequest object specifying the URL to download. Sends and loads data from the specified URL. The data can be received as text, raw binary data, or URL-encoded variables, depending on the value you set for the dataFormat property. Note that the default value of the dataFormat property is text. If you want to send data to the specified URL, you can set the data property in the URLRequest object.

Note: If a file being loaded contains non-ASCII characters (as found in many non-English languages), it is recommended that you save the file with UTF-8 or UTF-16 encoding as opposed to a non-Unicode format like ASCII.

A SWF file in the local-with-filesystem sandbox may not load data from, or provide data to, a resource that is in the network sandbox.

By default, the calling SWF file and the URL you load must be in exactly the same domain. For example, a SWF file at www.adobe.com can load data only from sources that are also at www.adobe.com. To load data from a different domain, place a URL policy file on the server hosting the data.

You cannot connect to commonly reserved ports. For a complete list of blocked ports, see "Restricting Networking APIs" in the ActionScript 3.0 Developer's Guide.

In Flash Player 10 and later, if you use a multipart Content-Type (for example "multipart/form-data") that contains an upload (indicated by a "filename" parameter in a "content-disposition" header within the POST body), the POST operation is subject to the security rules applied to uploads:

  • The POST operation must be performed in response to a user-initiated action, such as a mouse click or key press.
  • If the POST operation is cross-domain (the POST target is not on the same server as the SWF file that is sending the POST request), the target server must provide a URL policy file that permits cross-domain access.

Also, for any multipart Content-Type, the syntax must be valid (according to the RFC2046 standards). If the syntax appears to be invalid, the POST operation is subject to the security rules applied to uploads.

For more information related to security, see the Flash Player Developer Center Topic: Security.

In the following example, an XML files is loaded and the content of its elements' first arguments are displayed in a text field.

A URLRequest object is created to identify the location of the XML file, which for this example is in the same directory as the SWF file. The file is loaded in a try...catch block in order to catch any error that may occur. (Here we catch the SecurityError errors.) If an IO_ERROR event occurs, the errorHandler() method is invoked, which writes an error message in the xmlTextField text field. Once the XML file data is received and place in the data property of the loader URLLoader object, the Event.COMPLETE event is dispatched and the loaderCompleteHandler() method is invoked.

In the loaderCompleteHandler() method, a try...catch block is used to catch any parsing error that may occur while converting the loaded data from the file into an XML object. The readNodes() method then recursively goes through all the elements in the nodes of the XML document and appends the xmlTextField text field with a list of the first attributes of all the elements.

package { import flash.display.Sprite; import flash.events.Event; import flash.net.URLLoader; import flash.net.URLRequest; import flash.text.TextField; import flash.text.TextFieldAutoSize; import flash.xml.*; import flash.events.IOErrorEvent; public class URLLoader_loadExample extends Sprite { private var xmlTextField:TextField = new TextField(); private var externalXML:XML; private var loader:URLLoader; public function URLLoader_loadExample() { var request:URLRequest = new URLRequest("xmlFile.xml"); loader = new URLLoader(); try { loader.load(request); } catch (error:SecurityError) { trace("A SecurityError has occurred."); } loader.addEventListener(IOErrorEvent.IO_ERROR, errorHandler); loader.addEventListener(Event.COMPLETE, loaderCompleteHandler); xmlTextField.x = 10; xmlTextField.y = 10; xmlTextField.background = true; xmlTextField.autoSize = TextFieldAutoSize.LEFT; addChild(xmlTextField); } private function loaderCompleteHandler(event:Event):void { try { externalXML = new XML(loader.data); readNodes(externalXML); } catch (e:TypeError) { trace("Could not parse the XML file."); } } private function readNodes(node:XML):void { for each (var element:XML in node.elements()) { xmlTextField.appendText(element.attributes()[0] + "\n"); readNodes(element); } } private function errorHandler(e:IOErrorEvent):void { xmlTextField.text = "Had problem loading the XML File."; } } }
URLRequestHeaderURLRequest.requestHeadersURLRequest.dataURLRequest.digestcompleteflash.events:EventDispatched after data has loaded successfully. Dispatched after data has loaded successfully.httpStatusflash.events:HTTPStatusEventIf access is over HTTP, and the current Flash Player environment supports obtaining status codes, you may receive these events in addition to any complete or error event. If access is over HTTP, and the current Flash Player environment supports obtaining status codes, you may receive these events in addition to any complete or error event.ioErrorflash.events:IOErrorEventThe load operation could not be completed. The load operation could not be completed.progressflash.events:ProgressEventDispatched when data is received as the download operation progresses. Dispatched when data is received as the download operation progresses.securityErrorflash.events:SecurityErrorEventA load operation attempted to retrieve data from a server outside the caller's security sandbox. This may be worked around using a policy file on the server. A load operation attempted to retrieve data from a server outside the caller's security sandbox.securityErrorflash.events:SecurityErrorEventA load operation attempted to load a SWZ file (a Adobe platform component), but the certificate is invalid or the digest does not match the component. A load operation attempted to load a SWZ file (a Adobe platform component), but the certificate is invalid or the digest does not match the component.openflash.events:EventDispatched when a load operation commences. Dispatched when a load operation commences.httpResponseStatusflash.events:HTTPStatusEventDispatched if a call to the load() method attempts to access data over HTTP and Adobe AIR is able to detect and return the status code for the request. Dispatched if a call to the load() method attempts to access data over HTTP and Adobe AIR is able to detect and return the status code for the request.
bytesLoaded Indicates the number of bytes that have been loaded thus far during the load operation.0uint Indicates the number of bytes that have been loaded thus far during the load operation. bytesTotal Indicates the total number of bytes in the downloaded data.0uint Indicates the total number of bytes in the downloaded data. This property contains 0 while the load operation is in progress and is populated when the operation is complete. Also, a missing Content-Length header will result in bytesTotal being indeterminate. dataFormat Controls whether the downloaded data is received as text (URLLoaderDataFormat.TEXT), raw binary data (URLLoaderDataFormat.BINARY), or URL-encoded variables (URLLoaderDataFormat.VARIABLES).textStringURLLoaderDataFormat.TEXT Controls how the downloaded data is received. Controls whether the downloaded data is received as text (URLLoaderDataFormat.TEXT), raw binary data (URLLoaderDataFormat.BINARY), or URL-encoded variables (URLLoaderDataFormat.VARIABLES).

If the value of the dataFormat property is URLLoaderDataFormat.TEXT, the received data is a string containing the text of the loaded file.

If the value of the dataFormat property is URLLoaderDataFormat.BINARY, the received data is a ByteArray object containing the raw binary data.

If the value of the dataFormat property is URLLoaderDataFormat.VARIABLES, the received data is a URLVariables object containing the URL-encoded variables.

The following example shows how you can load external text files. Use the URLRequest and URLLoader classes, and then listen for the complete event. Example provided by ActionScriptExamples.com. var PATH:String = "lorem.txt"; var urlRequest:URLRequest = new URLRequest(PATH); var urlLoader:URLLoader = new URLLoader(); urlLoader.dataFormat = URLLoaderDataFormat.TEXT; // default urlLoader.addEventListener(Event.COMPLETE, urlLoader_complete); urlLoader.load(urlRequest); function urlLoader_complete(evt:Event):void { textArea.text = urlLoader.data; }
URLLoaderDataFormat
data The data received from the load operation. The data received from the load operation. This property is populated only when the load operation is complete. The format of the data depends on the setting of the dataFormat property:

If the dataFormat property is URLLoaderDataFormat.TEXT, the received data is a string containing the text of the loaded file.

If the dataFormat property is URLLoaderDataFormat.BINARY, the received data is a ByteArray object containing the raw binary data.

If the dataFormat property is URLLoaderDataFormat.VARIABLES, the received data is a URLVariables object containing the URL-encoded variables.

The following example shows how you can load an external text file with URL encoded variables into an ActionScript 3.0 document using the URLLoader class and setting the dataFormat property to the URLLoaderDataFormat.VARIABLES constant ("variables"). Example provided by ActionScriptExamples.com. //params.txt is a local file that includes: firstName=Tom&lastName=Jones var lbl:TextField = new TextField(); var urlRequest:URLRequest = new URLRequest("params.txt"); var urlLoader:URLLoader = new URLLoader(); urlLoader.dataFormat = URLLoaderDataFormat.VARIABLES; urlLoader.addEventListener(Event.COMPLETE, urlLoader_complete); urlLoader.load(urlRequest); function urlLoader_complete(evt:Event):void { lbl.text = urlLoader.data.lastName + "," + urlLoader.data.firstName; addChild(lbl); }
URLLoaderDataFormatURLLoader.dataFormat
IDynamicPropertyOutput This interface controls the serialization of dynamic properties of dynamic objects. This interface controls the serialization of dynamic properties of dynamic objects. You use this interface with the IDynamicPropertyWriter interface and the ObjectEncoding.dynamicPropertyWriter property. IDynamicPropertyWriterObjectEncoding.dynamicPropertyWriterwriteDynamicProperty Adds a dynamic property to the binary output of a serialized object.nameStringThe name of the property. You can use this parameter either to specify the name of an existing property of the dynamic object or to create a new property. valueThe value to write to the specified property. Adds a dynamic property to the binary output of a serialized object. When the object is subsequently read (using a method such as readObject), it contains the new property. You can use this method to exclude properties of dynamic objects from serialization; to write values to properties of dynamic objects; or to create new properties for dynamic objects. IDynamicPropertyWriterObjectEncoding.dynamicPropertyWriterNetStreamPlayOptions The NetStreamPlayOptions class specifies the various options that can be passed to the NetStream.play2() method.The NetStreamPlayOptions class specifies the various options that can be passed to the NetStream.play2() method. flash.events:EventDispatcher The NetStreamPlayOptions class specifies the various options that can be passed to the NetStream.play2() method. You pass a NetStreamPlayOptions object to play2(), and the properties of the class specify the various options. The primary use case for this class is to implement transitions between streams dynamically, either to switch to streams of different bit rates and sizes or to swap to different content in a playlist. NetStreamPlayOptions Creates a NetStreamPlayOptions object to specify the options that are passed to the NetStream.play2() method. Creates a NetStreamPlayOptions object to specify the options that are passed to the NetStream.play2() method. NetStream.play2()len The duration of playback, in seconds, for the stream specified in streamName.NumberThe duration of playback, in seconds, for the stream specified in streamName. The duration of playback, in seconds, for the stream specified in streamName. The default value is -1, which means that Flash Player plays a live stream until it is no longer available or plays a recorded stream until it ends. If you pass 0 for len, Flash Player plays the single frame that is start seconds from the beginning of a recorded stream (assuming that start is equal to or greater than 0).

If you pass a positive number for len, Flash Player plays a live stream for len seconds after it becomes available, or plays a recorded stream for len seconds. (If a stream ends before len seconds, playback ends when the stream ends.)

If you pass a negative number other than -1 for len, Flash Player interprets the value as if it were -1.

NetStream.play()NetStream.play2()start
offset The time in seconds in the stream playback at which the switch to a new stream should be made.Number The time in seconds in the stream playback at which the switch to a new stream should be made. The offset parameter is used when a NetStream.play2() call is made with the NetStreamPlayTransitions.SWITCH transition mode. Flash Media Server looks for the nearest switch point after the specified offset time and starts streaming the new stream from that point onwards.

Fast switch

When this property is specified, Flash Media Server pre-empts the current stream and starts streaming the new stream from the specified index position immediately, without waiting to find a keyframe. Any data after the offset already buffered from a previous stream is flushed. This technique can switch to a new stream more quickly than standard switching, because the buffered data from an older stream doesn't have to play out.

The default value of offset is -1, which is fast switch mode. In this mode, switching occurs at the first available keyframe after netstream.time + 3, which is about 3 seconds later than the playback point.

The offset value must be higher than the current playback time (Netstream.time) If the value is less, a NetStream.Play.Failed status event is sent.

For more information, see "Fast switching between streams" in the Adobe Flash Media Server Developer's Guide.

startNetStream.play()NetStream.play2()NetStream.timeNetStreamPlayTransitions.SWITCH
oldStreamName The name of the old stream or the stream to transition from.String The name of the old stream or the stream to transition from. When NetStream.play2() is used to simply play a stream (not perform a transition), the value of this property should be either null or undefined. Otherwise, specify the stream to transition from. streamNameNetStream.play()NetStream.play2()start The start time, in seconds, for streamName.NumberThe start time, in seconds, for streamName. The start time, in seconds, for streamName. Valid values are -2, -1, and 0.

The default value for start is -2, which means that Flash Player first tries to play the live stream specified in streamName. If a live stream of that name is not found, Flash Player plays the recorded stream specified in streamName. If neither a live nor a recorded stream is found, Flash Player opens a live stream named streamName, even though no one is publishing on it. When someone does begin publishing on that stream, Flash Player begins playing it.

If you pass -1 for start, Flash Player plays only the live stream specified in streamName. If no live stream is found, Flash Player waits for it indefinitely if len is set to -1; if len is set to a different value, Flash Player waits for len seconds before it begins playing the next item in the playlist.

If you pass 0 or a positive number for start, Flash Player plays only a recorded stream named streamName, beginning start seconds from the beginning of the stream. If no recorded stream is found, Flash Player begins playing the next item in the playlist immediately.

If you pass a negative number other than -1 or -2 for start, Flash Player interprets the value as if it were -2.

NetStream.play()NetStream.play2()len
streamName The name of the new stream to transition to or to play.String The name of the new stream to transition to or to play. When oldStreamName is null or undefined, calling NetStream.play2() simply starts playback of streamName. If oldStreamName is specified, calling NetStream.play2() transitions oldStreamName to streamName using the transition mode specified in the transition property. oldStreamNameNetStream.play()NetStream.play2()transition The mode in which streamName is played or transitioned to.StringThe mode in which streamName is played or transitioned to. The mode in which streamName is played or transitioned to. Possible values are constants from the NetStreamPlayTransitions class. Depending on whether Netstream.play2() is called to play or transition a stream, the transition mode results in different behaviors. For more information on the transition modes, see the NetStreamPlayTransitions class. NetStreamPlayTransitionsNetStream.play2()
NetStreamMulticastInfo The NetStreamMulticastInfo class specifies various Quality of Service (QoS) statistics related to a NetStream object's underlying RTMFP Peer-to-Peer and IP Multicast stream transport.Object The NetStreamMulticastInfo class specifies various Quality of Service (QoS) statistics related to a NetStream object's underlying RTMFP Peer-to-Peer and IP Multicast stream transport. A NetStreamMulticastInfo object is returned by the NetStream.multicastInfo property.

Properties that return numbers represent totals computed from the beginning of the multicast stream. These types of properties include the number of media bytes sent or the number of media fragment messages received. Properties that are rates represent a snapshot of the current rate averaged over a few seconds. These types of properties include the rate at which a local node is receiving data.

To see a list of values contained in the NetStreamMulticastInfo object, use the NetStreamMulticastInfo.toString() method.

toString()flash.net.NetStream.multicastInfotoString Returns a string listing the properties of the NetStreamMulticastInfo object.A string containing the values of the properties of the NetStreamMulticastInfo object String Returns a string listing the properties of the NetStreamMulticastInfo object. bytesPushedFromPeers Specifies the number of media bytes that were proactively pushed from peers and received by the local node.Number Specifies the number of media bytes that were proactively pushed from peers and received by the local node. bytesRequestedFromPeersfragmentsPushedFromPeersfragmentsRequestedFromPeersbytesPushedToPeers Specifies the number of media bytes that the local node has proactively pushed to peers.Number Specifies the number of media bytes that the local node has proactively pushed to peers. bytesRequestedByPeersfragmentsPushedToPeersfragmentsRequestedByPeersbytesReceivedFromIPMulticast Specifies the number of media bytes that the local node has received from IP Multicast.Number Specifies the number of media bytes that the local node has received from IP Multicast. bytesReceivedFromServerfragmentsReceivedFromIPMulticastfragmentsReceivedFromServerreceiveDataBytesPerSecondFromIPMulticastbytesReceivedFromServer Specifies the number of media bytes that the local node has received from the server.Number Specifies the number of media bytes that the local node has received from the server. bytesReceivedFromIPMulticastfragmentsReceivedFromIPMulticastfragmentsReceivedFromServerreceiveDataBytesPerSecondFromServerbytesRequestedByPeers Specifies the number of media bytes that the local node has sent to peers in response to requests from those peers for specific fragments.Number Specifies the number of media bytes that the local node has sent to peers in response to requests from those peers for specific fragments. bytesPushedToPeersfragmentsPushedToPeersfragmentsRequestedByPeersbytesRequestedFromPeers Specifies the number of media bytes that the local node requested and received from peers.Number Specifies the number of media bytes that the local node requested and received from peers. bytesPushedFromPeersfragmentsPushedFromPeersfragmentsRequestedFromPeersfragmentsPushedFromPeers Specifies the number of media fragment messages that were proactively pushed from peers and received by the local node.Number Specifies the number of media fragment messages that were proactively pushed from peers and received by the local node. bytesPushedFromPeersbytesRequestedFromPeersfragmentsRequestedFromPeersfragmentsPushedToPeers Specifies the number of media fragment messages that the local node has proactively pushed to peers.Number Specifies the number of media fragment messages that the local node has proactively pushed to peers. bytesPushedToPeersbytesRequestedByPeersfragmentsRequestedByPeersfragmentsReceivedFromIPMulticast Specifies the number of media fragment messages that the local node has received from IP Multicast.Number Specifies the number of media fragment messages that the local node has received from IP Multicast. bytesReceivedFromIPMulticastbytesReceivedFromServerfragmentsReceivedFromServerreceiveDataBytesPerSecondFromIPMulticastfragmentsReceivedFromServer Specifies the number of media fragment messages that the local node has received from the server.Number Specifies the number of media fragment messages that the local node has received from the server. bytesReceivedFromIPMulticastbytesReceivedFromServerfragmentsReceivedFromIPMulticastreceiveDataBytesPerSecondFromServerfragmentsRequestedByPeers Specifies the number of media fragment messages that the local node has sent to peers in response to requests from those peers for specific fragments.Number Specifies the number of media fragment messages that the local node has sent to peers in response to requests from those peers for specific fragments. bytesPushedToPeersbytesRequestedByPeersfragmentsPushedToPeersfragmentsRequestedFromPeers Specifies the number of media fragment messages that the local node requested and received from peers.Number Specifies the number of media fragment messages that the local node requested and received from peers. bytesPushedFromPeersbytesRequestedFromPeersfragmentsPushedFromPeersreceiveControlBytesPerSecond Specifies the rate at which the local node is receiving control overhead messages from peers, in bytes per second.Number Specifies the rate at which the local node is receiving control overhead messages from peers, in bytes per second. receiveDataBytesPerSecondreceiveDataBytesPerSecondFromServerreceiveDataBytesPerSecondFromIPMulticastsendControlBytesPerSecondreceiveDataBytesPerSecondFromIPMulticast Specifies the rate at which the local node is receiving data from IP Multicast, in bytes per second.Number Specifies the rate at which the local node is receiving data from IP Multicast, in bytes per second. receiveControlBytesPerSecondreceiveDataBytesPerSecondreceiveDataBytesPerSecondFromServersendDataBytesPerSecondreceiveDataBytesPerSecondFromServer Specifies the rate at which the local node is receiving media data from the server, in bytes per second.Number Specifies the rate at which the local node is receiving media data from the server, in bytes per second. receiveControlBytesPerSecondreceiveDataBytesPerSecondreceiveDataBytesPerSecondFromIPMulticastsendDataBytesPerSecondreceiveDataBytesPerSecond Specifies the rate at which the local node is receiving media data from peers, from the server, and over IP multicast, in bytes per second.Number Specifies the rate at which the local node is receiving media data from peers, from the server, and over IP multicast, in bytes per second. receiveControlBytesPerSecondreceiveDataBytesPerSecondFromIPMulticastreceiveDataBytesPerSecondFromServersendDataBytesPerSecondsendControlBytesPerSecondToServer Specifies the rate at which the local node is sending control overhead messages to the server, in bytes per second.Number Specifies the rate at which the local node is sending control overhead messages to the server, in bytes per second. receiveDataBytesPerSecondFromServersendControlBytesPerSecondsendDataBytesPerSecondsendControlBytesPerSecond Specifies the rate at which the local node is sending control overhead messages to peers and the server, in bytes per second.Number Specifies the rate at which the local node is sending control overhead messages to peers and the server, in bytes per second. receiveControlBytesPerSecondsendControlBytesPerSecondToServersendDataBytesPerSecondsendDataBytesPerSecond Specifies the rate at which media data is being sent by the local node to peers, in bytes per second.Number Specifies the rate at which media data is being sent by the local node to peers, in bytes per second. receiveDataBytesPerSecondsendControlBytesPerSecondsendControlBytesPerSecondToServer
NetworkInfo The NetworkInfo class provides information about the network interfaces on a computer.flash.events:EventDispatcher The NetworkInfo class provides information about the network interfaces on a computer.

AIR profile support: This feature is supported on all desktop operating systems and AIR for TV devices, but is not supported on all mobile devices. You can test for support at run time using the NetworkInfo.isSupported property. See AIR Profile Support for more information regarding API support across multiple profiles.

The NetworkInfo object is a singleton. To get the single NetworkInfo object, use the static NetworkInfo.networkInfo property. Do not call the class constructor, new NetworkInfo().

Most computers have one or more interfaces, such as a wired and a wireless network interface. Additional interfaces such as VPN, loopback, or virtual interfaces can also be present.

A NetworkInfo object dispatches a change event when the available interfaces change. Call the findInterfaces() method to determine the most current network information.

Note: The NativeApplication object also dispatches network change events.

NetworkInterface classInterfaceAddress classnetworkChange Dispatched when the network interfaces have changed.flash.events.Event.NETWORK_CHANGEflash.events.Event Dispatched when the network interfaces have changed. findInterfaces Returns the list of network interfaces associated with this machine.An array of NetworkInterface objects Returns the list of network interfaces associated with this machine. isSupported Indicates whether access to network interface information is supported on the client system.Boolean Indicates whether access to network interface information is supported on the client system. networkInfo The singleton instance of the NetworkInfo object.flash.net:NetworkInfoIf content running outside the AIR application security sandbox accesses this property. SecurityErrorSecurityError The singleton instance of the NetworkInfo object.
URLVariables The URLVariables class allows you to transfer variables between an application and a server.Object The URLVariables class allows you to transfer variables between an application and a server. Use URLVariables objects with methods of the URLLoader class, with the data property of the URLRequest class, and with flash.net package functions. The following example opens the remote application hosted at http://www.[yourDomain].com/application.jsp in a new browser window and passes data about a user session, captured in a URLVariables object, to the application.

Highlights of the example follow:

  1. The constructor function creates a URLRequest instance named request, taking the URL of the remote application as a parameter.
  2. A URLVariables object is created and two of its properties are assigned values.
  3. The URLVariables object is assigned to the data property of the URLRequest object.
  4. The example calls navigateToURL, which opens a new browser window to the remote application's URL.

Note: To run the example, the remote application URL in the example must be replaced with a working URL. Additionally, you would need server code to process the information captured by Flash Player in the URLVariables object.

package { import flash.display.Sprite; import flash.net.navigateToURL; import flash.net.URLRequest; import flash.net.URLVariables; public class URLVariablesExample extends Sprite { public function URLVariablesExample() { var url:String = "http://www.[yourDomain].com/application.jsp"; var request:URLRequest = new URLRequest(url); var variables:URLVariables = new URLVariables(); variables.exampleSessionId = new Date().getTime(); variables.exampleUserLabel = "guest"; request.data = variables; navigateToURL(request); } } }
URLLoaderURLVariables Creates a new URLVariables object.sourceStringnullA URL-encoded string containing name/value pairs. Creates a new URLVariables object. You pass URLVariables objects to the data property of URLRequest objects.

If you call the URLVariables constructor with a string, the decode() method is automatically called to convert the string to properties of the URLVariables object.

decode Converts the variable string to properties of the specified URLVariables object.The source parameter must be a URL-encoded query string containing name/value pairs. ErrorErrorsourceStringA URL-encoded query string containing name/value pairs. Converts the variable string to properties of the specified URLVariables object.

This method is used internally by the URLVariables events. Most users do not need to call this method directly.

The following examples show how you can parse URL encoded strings. Example provided by ActionScriptExamples.com. // The first method passes the string to be decoded to the URLVariables class constructor: var urlVariables:URLVariables = new URLVariables("firstName=Tom&lastName=Jones"); lbl.text = urlVariables.lastName + "," + urlVariables.firstName; // The second method uses the decode() method to parse the URL encoded string: var urlVariables:URLVariables = new URLVariables(); urlVariables.decode("firstName=Tom&lastName=Jones"); lbl.text = urlVariables.lastName + "," + urlVariables.firstName;
toString Returns a string containing all enumerable variables, in the MIME content encoding application/x-www-form-urlencoded.A URL-encoded string containing name/value pairs. String Returns a string containing all enumerable variables, in the MIME content encoding application/x-www-form-urlencoded.
IDynamicPropertyWriter This interface is used with the IDynamicPropertyOutput interface to control the serialization of dynamic properties of dynamic objects. This interface is used with the IDynamicPropertyOutput interface to control the serialization of dynamic properties of dynamic objects. To use this interface, assign an object that implements the IDynamicPropertyWriter interface to the ObjectEncoding.dynamicPropertyWriter property. IDynamicPropertyOutputObjectEncoding.dynamicPropertyWriterwriteDynamicProperties Writes the name and value of an IDynamicPropertyOutput object to an object with dynamic properties.objObjectThe object to write to. outputflash.net:IDynamicPropertyOutputThe IDynamicPropertyOutput object that contains the name and value to dynamically write to the object. Writes the name and value of an IDynamicPropertyOutput object to an object with dynamic properties. If ObjectEncoding.dynamicPropertyWriter is set, this method is invoked for each object with dynamic properties. IDynamicPropertyOutputObjectEncoding.dynamicPropertyWriterDatagramSocket The DatagramSocket class enables code to send and receive Universal Datagram Protocol (UDP) packets.flash.events:EventDispatcher The DatagramSocket class enables code to send and receive Universal Datagram Protocol (UDP) packets.

AIR profile support: This feature is supported on all desktop operating systems, but is not supported on mobile devices or AIR for TV devices. You can test for support at run time using the DatagramSocket.isSupported property. See AIR Profile Support for more information regarding API support across multiple profiles.

Datagram packets are individually transmitted between the source and destination. Packets can arrive in a different order than they were sent. Packets lost in transmission are not retransmitted, or even detected.

Data sent using a datagram socket is not automatically broken up into packets of transmittable size. If you send a UDP packet that exceeds the maximum transmission unit (MTU) size, network discards the packet (without warning). The limiting MTU is the smallest MTU of any interface, switch, or router in the transmission path. You can use the NetworkInterface class to determine the MTU of the local interface, but other nodes in the network can have different MTU values.

The Socket class uses TCP which provides guaranteed packet delivery and automatically divides and reassembles large packets. TCP also provides better network bandwidth management. These features mean that data sent using a TCP socket incurs higher latency, but for most uses, the benefits of TCP far outweigh the costs. Most network communication should use the Socket class rather than the DatagramSocket class.

The DatagramSocket class is useful for working with applications where a small transmission latency is important and packet loss is tolerable. For example, network operations in voice-over-IP (VoIP) applications and real-time, multiplayer games can often benefit from UDP. The DatagramSocket class is also useful for some server-side applications. Since UDP is a stateless protocol, a server can handle more requests from more clients than it can with TCP.

The DatagramSocket class can only be used in Adobe AIR applications and only in the application security sandbox.

For more information related to security, see the Flash Player Developer Center Topic: Security.

package { import flash.display.Sprite; import flash.events.DatagramSocketDataEvent; import flash.events.Event; import flash.events.MouseEvent; import flash.events.TimerEvent; import flash.net.DatagramSocket; import flash.text.TextField; import flash.text.TextFieldAutoSize; import flash.text.TextFieldType; import flash.utils.ByteArray; import flash.utils.Timer; public class DatagramSocketExample extends Sprite { private var datagramSocket:DatagramSocket = new DatagramSocket();; private var localIP:TextField; private var localPort:TextField; private var logField:TextField; private var targetIP:TextField; private var targetPort:TextField; private var message:TextField; public function DatagramSocketExample() { setupUI(); } private function bind( event:Event ):void { if( datagramSocket.bound ) { datagramSocket.close(); datagramSocket = new DatagramSocket(); } datagramSocket.bind( parseInt( localPort.text ), localIP.text ); datagramSocket.addEventListener( DatagramSocketDataEvent.DATA, dataReceived ); datagramSocket.receive(); log( "Bound to: " + datagramSocket.localAddress + ":" + datagramSocket.localPort ); } private function dataReceived( event:DatagramSocketDataEvent ):void { //Read the data from the datagram log("Received from " + event.srcAddress + ":" + event.srcPort + "> " + event.data.readUTFBytes( event.data.bytesAvailable ) ); } private function send( event:Event ):void { //Create a message in a ByteArray var data:ByteArray = new ByteArray(); data.writeUTFBytes( message.text ); //Send a datagram to the target try { datagramSocket.send( data, 0, 0, targetIP.text, parseInt( targetPort.text )); log( "Sent message to " + targetIP.text + ":" + targetPort.text ); } catch ( error:Error ) { log( error.message ); } } private function log( text:String ):void { logField.appendText( text + "\n" ); logField.scrollV = logField.maxScrollV; trace( text ); } private function setupUI():void { targetIP = createTextField( 10, 10, "Target IP:", "192.168.0.1" ); targetPort = createTextField( 10, 35, "Target port:", "8989" ); message = createTextField( 10, 60, "Message:", "Lucy can't drink milk." ); localIP = createTextField( 10, 85, "Local IP", "0.0.0.0"); localPort = createTextField( 10, 110, "Local port:", "0" ); createTextButton( 250, 135, "Bind", bind ); createTextButton( 300, 135, "Send", send ); logField = createTextField( 10, 160, "Log:", "", false, 200 ) this.stage.nativeWindow.activate(); } private function createTextField( x:int, y:int, label:String, defaultValue:String = '', editable:Boolean = true, height:int = 20 ):TextField { var labelField:TextField = new TextField(); labelField.text = label; labelField.type = TextFieldType.DYNAMIC; labelField.width = 180; labelField.x = x; labelField.y = y; var input:TextField = new TextField(); input.text = defaultValue; input.type = TextFieldType.INPUT; input.border = editable; input.selectable = editable; input.width = 280; input.height = height; input.x = x + labelField.width; input.y = y; this.addChild( labelField ); this.addChild( input ); return input; } private function createTextButton( x:int, y:int, label:String, clickHandler:Function ):TextField { var button:TextField = new TextField(); button.htmlText = "<u><b>" + label + "</b></u>"; button.type = TextFieldType.DYNAMIC; button.selectable = false; button.width = 180; button.x = x; button.y = y; button.addEventListener( MouseEvent.CLICK, clickHandler ); this.addChild( button ); return button; } } }
RFC 768Socket classXMLSocket classServerSocket classioError Dispatched when this socket receives an I/O error.flash.events.IOErrorEvent.IOERRORflash.events.IOErrorEventDispatched when this socket receives an I/O error. Dispatched when this socket receives an I/O error. data Dispatched when this socket receives a packet of data.flash.events.DatagramSocketDataEvent.DATAflash.events.DatagramSocketDataEvent Dispatched when this socket receives a packet of data. close Dispatched when the operating system closes this socket.flash.events.Event.CLOSEflash.events.Event Dispatched when the operating system closes this socket.

The close event is not dispatched when the DatagramSocket close() method is called.

DatagramSocket Creates a DatagramSocket object.if content outside the AIR application security sandbox attempts to create a DatagramSocket object. SecurityErrorSecurityError Creates a DatagramSocket object. bind Binds this socket to the specified local address and port.This error occurs when localPort is less than 0 or greater than 65535. RangeErrorRangeErrorThis error occurs when localAddress is not a syntactically well-formed IP address. ArgumentErrorArgumentErrorThis error occurs if the socket cannot be bound, such as when:
  1. localPort is already in use by another socket.
  2. the user account under which the application is running doesn't have sufficient system privileges to bind to the specified port. (Privilege issues typically occur when localPort < 1024.)
  3. This DatagramSocket object is already bound.
  4. This DatagramSocket object has been closed.
IOErrorflash.errors:IOError
This error occurs when localAddress is not a valid local address. ErrorErrorlocalPortint0The number of the port to bind to on the local computer. If localPort, is set to 0 (the default), the next available system port is bound. Permission to connect to a port number below 1024 is subject to the system security policy. On Mac and Linux systems, for example, the application must be running with root privileges to connect to ports below 1024. localAddressString0.0.0.0The IP address on the local machine to bind to. This address can be an IPv4 or IPv6 address. If localAddress is set to 0.0.0.0 (the default), the socket listens on all available IPv4 addresses. To listen on all available IPv6 addresses, you must specify "::" as the localAddress argument. To use an IPv6 address, the computer and network must both be configured to support IPv6. Furthermore, a socket bound to an IPv4 address cannot connect to a socket with an IPv6 address. Likewise, a socket bound to an IPv6 address cannot connect to a socket with an IPv4 address. The type of address must match.
Binds this socket to the specified local address and port.

The bind() method executes synchronously. The bind operation completes before the next line of code is executed.

The following example illustrates various ways to bind a DatagramSocket object: udpSocket.bind(); //bind to any available port, listen on all IPv4 addresses udpSocket.bind( 0, "0.0.0.0" ); //same as above udpSocket.bind( 0, "127.0.0.1" ); //any available port on the localhost address udpSocket.bind( 8989, "192.168.0.1" ); //port 8989 on a particular IPv4 address udpSocket.bind( 0, "::" ); //any available port on all IPv6 address udpSocket.bind( 8989, "::1" ); //port 8989 on the IPv6 localhost address udpSocket.bind( 8989, "2001:1890:110b:1e19:f06b:72db:7026:3d7a" ); //port 8989 on a particular IPv6 address
close Closes the socket.If the socket cannot be closed (because of an internal, networking, or operating system error), or if the socket is not open. IOErrorflash.errors:IOError Closes the socket.

The socket is disconnected from the remote machine and unbound from the local machine. A closed socket cannot be reused.

connect Connects the socket to a specified remote address and port.This error occurs when localPort is less than 1 or greater than 65535. RangeErrorRangeErrorThis error occurs when localAddress is not a syntactically valid address. Or when a default route address ('0.0.0.0' or '::') is used. ArgumentErrorArgumentErrorThis error occurs if the socket cannot be connected, such as when bind() has not been called before the call to connect() and default binding to the remote address family is not possible. IOErrorflash.errors:IOErrorremoteAddressStringThe IP address of the remote machine with which to establish a connection. This address can be an IPv4 or IPv6 address. If bind() has not been called, the address family of the remoteAddress, IPv4 or IPv6, is used when calling the default bind(). remotePortintThe port number on the remote machine used to establish a connection. Connects the socket to a specified remote address and port.

When a datagram socket is "connected," datagram packets can only be sent to and received from the specified target. Packets from other sources are ignored. Connecting a datagram socket is not required. Establishing a connection can remove the need to filter out extraneous packets from other sources. However, a UDP socket connection is not a persistent network connection (as it is for a TCP connection). It is possible that the remote end of the socket does not even exist.

If the bind() method has not been called, the socket is automatically bound to the default local address and port.

receive Enables this DatagramSocket object to receive incoming packets on the bound IP address and port. Enables this DatagramSocket object to receive incoming packets on the bound IP address and port.

The function returns immediately. The DatagramSocket object dispatches a data event when a data packet is received.

dataflash.events:DatagramSocketDataEventwhen a UDP packet is received. when a UDP packet is received.
send Sends packet containing the bytes in the ByteArray using UDP.This error occurs when port is less than 1 or greater than 65535. RangeErrorRangeErrorIf the socket is not connected and address is not a well-formed IP address. ArgumentErrorArgumentErrorThis error occurs:
  1. If bind() has not been called, and when default binding to the destination address family is not possible.
  2. On some operating systems, an IOError is thrown if the connect() method is called when an ICMP "destination unreachable" message has already been received from the target host. (Thus, the error is thrown on the second failed attempt to send data, not the first.) Other operating systems, such as Windows, disregard these ICMP messages, so no error is thrown.
IOErrorflash.errors:IOError
when the bytes parameter is null. ErrorErrorIf offset is greater than the length of the ByteArray specified in bytes or if the amount of data specified to be written by offset plus length exceeds the data available. RangeErrorRangeErrorIf the address or port parameters are specified when the socket has already been connected. IllegalOperationErrorflash.errors:IllegalOperationErrorbytesflash.utils:ByteArraya ByteArray containing the packet data. offsetuint0The zero-based offset into the bytes ByteArray object at which the packet begins. lengthuint0The number of bytes in the packet. The default value of 0 causes the entire ByteArray to be sent, starting at the value specified by the offset parameter. addressStringnullThe IPv4 or IPv6 address of the remote machine. An address is required if one has not already been specified using the connect() method. portint0The port number on the remote machine. A value greater than 0 and less than 65536 is required if the port has not already been specified using the connect() method.
Sends packet containing the bytes in the ByteArray using UDP.

If the socket is connected, the packet is sent to the remote address and port specified in the connect() method and no destination IP address and port can be specified. If the socket is not connected, the packet is sent to the specified address and port and you must supply valid values for address and port. If the bind() method has not been called, the socket is automatically bound to the default local address and port.

Note: Sending data to a broadcast address is not supported.

bound Indicates whether this socket object is currently bound to a local address and port.Boolean Indicates whether this socket object is currently bound to a local address and port. bind()connected Indicates whether this socket object is currently connected to a remote address and port.Boolean Indicates whether this socket object is currently connected to a remote address and port.

Note: A value of true does not mean that a remote computer is listening on the connected address and port. It only means that this DataGramSocket object will only send data to or receive data from that address and port.

connect()
isSupported Indicates whether or not DatagramSocket features are supported in the run-time environment.Boolean Indicates whether or not DatagramSocket features are supported in the run-time environment. localAddress The IP address this socket is bound to on the local machine.String The IP address this socket is bound to on the local machine. bind()localPort The port this socket is bound to on the local machine.int The port this socket is bound to on the local machine. bind()remoteAddress The IP address of the remote machine to which this socket is connected.String The IP address of the remote machine to which this socket is connected. connect()remotePort The port on the remote machine to which this socket is connected.int The port on the remote machine to which this socket is connected. connect()
NetGroupSendResult The NetGroupSendResult class is an enumeration of constant values used for the return value of the Directed Routing methods associated with a NetGroup instance.Object The NetGroupSendResult class is an enumeration of constant values used for the return value of the Directed Routing methods associated with a NetGroup instance. flash.net.NetGroup.sendToNearest()flash.net.NetGroup.sendToNeighbor()flash.net.NetGroup.sendToAllNeighbors()ERROR Indicates an error occurred (such as no permission) when using a Directed Routing method.errorString Indicates an error occurred (such as no permission) when using a Directed Routing method. NO_ROUTE Indicates no neighbor could be found to route the message toward its requested destination.no routeString Indicates no neighbor could be found to route the message toward its requested destination. SENT Indicates that a route was found for the message and it was forwarded toward its destination.sentString Indicates that a route was found for the message and it was forwarded toward its destination. URLRequestDefaults The URLRequestDefaults class includes static properties that you can set to define default values for the properties of the URLRequest class.Object The URLRequestDefaults class includes static properties that you can set to define default values for the properties of the URLRequest class. It also includes a static method, URLRequestDefaults.setLoginCredentialsForHost(), which lets you define default authentication credentials for requests. The URLRequest class defines the information to use in an HTTP request.

Any properties set in a URLRequest object override those static properties set for the URLRequestDefaults class.

URLRequestDefault settings only apply to content in the caller's application domain, with one exception: settings made by calling URLRequestDefaults.setLoginCredentialsForHost() apply to all application domains in the currently running application.

Only Adobe® AIR® content running in the application security sandbox can use the URLRequestDefaults class. Other content will result in a SecurityError being thrown when accessing the members or properties of this class.

URLRequestsetLoginCredentialsForHost Sets default user and password credentials for a selected host.The caller is not in the AIR application security sandbox. SecurityErrorSecurityErrorhostnameStringThe host name to which the user name and password are applied. This can be a domain, such as "www.example.com" or a domain and a port number, such as "www.example.com:80". Note that "example.com", "www.example.com", and "sales.example.com" are each considered unique hosts. userStringThe default user name to use in request authentication for the specified host. passwordStringThe default password to use in request authentication for the specified host. Sets default user and password credentials for a selected host. These settings apply for URLRequest objects in all application domains of the application, not only those in the application domain of the object calling this method (whereas the static properties of the URLRequest class apply to the caller's application domain only). This allows content in the entire application (regardless of the content's application domain) to be logged in when another part of the application logs in.

Note for applications running on Mac OS: On Mac OS, when you call this method, the application uses these credentials for the specified host until the application is closed, even if you subsequently call URLRequestDefaults.setLoginCredentialsForHost() for the same host. However, if a server rejects the credentials specified by this method, then a subsequent call to the URLRequestDefaults.setLoginCredentialsForHost() method (for the same host) will be recognized.

Note: This method does not apply to URLRequest objects used in file upload or RTMP requests.

authenticate The default setting for the authenticate property of URLRequest objects.BooleanThe caller is not in the AIR application security sandbox. SecurityErrorSecurityErrortrue The default setting for the authenticate property of URLRequest objects. Setting the authenticate property in a URLRequest object overrides this default setting.

Note: This setting does not apply to URLRequest objects used in file upload or RTMP requests.

URLRequest.authenticate
cacheResponse The default setting for the cacheResponse property of URLRequest objects.BooleanThe caller is not in the AIR application security sandbox. SecurityErrorSecurityErrortrue The default setting for the cacheResponse property of URLRequest objects. Setting the cacheResponse property in a URLRequest object overrides this default setting. When set to true, the default behavior for the AIR application is to use the operating system's HTTP cache. This setting does not apply to URLRequest objects used in file upload or RTMP requests. URLRequest.cacheResponsefollowRedirects The default setting for the followRedirects property of URLRequest objects.BooleanThe caller is not in the AIR application security sandbox. SecurityErrorSecurityErrortrue The default setting for the followRedirects property of URLRequest objects. Setting the followRedirects property in a URLRequest object overrides this default setting. This setting does not apply to URLRequest objects used in file upload or RTMP requests. URLRequest.followRedirectsidleTimeout The default setting for the idleTimeout property of URLRequest objects and HTMLLoader objects.NumberThe caller is not in the AIR application security sandbox. SecurityErrorSecurityErrorThe idleTimeout value is negative. RangeErrorRangeError0 The default setting for the idleTimeout property of URLRequest objects and HTMLLoader objects.

The idle timeout is the amount of time (in milliseconds) that the client waits for a response from the server, after the connection is established, before abandoning the request.

This defines the default idle timeout used by the URLRequest or HTMLLoader object. Setting the idleTimeout property in a URLRequest object or an HTMLLoader object overrides this default setting.

When this property is set to 0 (the default), the runtime uses the default idle timeout value defined by the operating system. The default idle timeout value varies between operating systems (such as Mac OS, Linux, or Windows) and between operating system versions.

This setting does not apply to URLRequest objects used in file upload or RTMP requests.

HTMLLoader.idleTimeoutURLRequest.idleTimeout
manageCookies The default setting for the manageCookies property of URLRequest objects.BooleanThe caller is not in the AIR application security sandbox. SecurityErrorSecurityErrortrue The default setting for the manageCookies property of URLRequest objects. Setting the manageCookies property in a URLRequest object overrides this default setting.

Note: This setting does not apply to URLRequest objects used in file upload or RTMP requests.

URLRequest.manageCookies
useCache The default setting for the useCache property of URLRequest objects.BooleanThe caller is not in the AIR application security sandbox. SecurityErrorSecurityErrortrue The default setting for the useCache property of URLRequest objects. Setting the useCache property in a URLRequest object overrides this default setting. This setting does not apply to URLRequest objects used in file upload or RTMP requests. URLRequest.useCacheuserAgent The default setting for the userAgent property of URLRequest objects.StringThe caller is not in the AIR application security sandbox. SecurityErrorSecurityError The default setting for the userAgent property of URLRequest objects. Setting the userAgent property in a URLRequest object overrides this default setting.

This is also the default user agent string for all HTMLLoader objects (used when you call the load() method of the HTMLLoader object). Setting the userAgent property of the HTMLLoader object overrides the URLRequestDefaults.userAgent setting.

This default value varies depending on the runtime operating system (such as Mac OS, Linux or Windows), the runtime language, and the runtime version, as in the following examples:

  • "Mozilla/5.0 (Macintosh; U; PPC Mac OS X; en) AppleWebKit/526.9+ (KHTML, like Gecko) AdobeAIR/1.5"
  • "Mozilla/5.0 (Windows; U; en) AppleWebKit/526.9+ (KHTML, like Gecko) AdobeAIR/1.5"
  • "Mozilla/5.0 (X11; U; Linux i686; en-US) AppleWebKit/526.9+ (KHTML, like Gecko) AdobeAIR/1.5"
flash.net.URLRequest.userAgentflash.html.HTMLLoader.userAgent
NetGroup Instances of the NetGroup class represent membership in an RTMFP group.flash.events:EventDispatcher Instances of the NetGroup class represent membership in an RTMFP group. Use this class to do the following:
  • Monitor Quality of Service. The info property contains a NetGroupInfo object whose properties provide QoS statistics for this group.
  • Posting. Call post() to broadcast ActionScript messages to all members of a group.
  • Direct routing. Call sendToNearest(), sendToNeighbor(), and sendToAllNeighbors() to send a short data message to a specific member of a peer-to-peer group. The source and the destination do not need to have a direct connection.
  • Object replication. Call addHaveObjects(), removeHaveObjects(), addWantObjects(), removeWantObjects(), writeRequestedObject(), and denyRequestedObject() to break up large data into pieces and replicate it to all nodes in a peer-to-peer group.

In the client-side NetGroup class, the NetConnection dispatches the following events:

  • NetGroup.Connect.Success
  • NetGroup.Connect.Failed
  • NetGroup.Connect.Rejected

The info.group property of the event object contains a reference to the event source (the NetGroup). The NetGroup dispatches all other events. In the server-side NetGroup class, the NetGroup dispatches all events.

For information about peer-assisted networking, see Basics of P2P in Flash by Adobe Evangelist Tom Krcha. For information about using groups with peer-assisted networking, see Social Media Experiences with Flash Media and RTMFP, also by Tom Krcha.

For information about the technical details behind peer-assisted networking, see P2P on the Flash Platform with RTMFP by Adobe Computer Scientist Matthew Kaufman.

This is a simple video chat application that uses peer-to-peer networking. The application connects over RTMFP to Flash Media Server. The server keeps the client applications' fingerprints and manages the peer group as clients connect. However, all data is sent between clients (peers) -- data is not sent back to the server.

When you run the application, you can enter any group name into the text input field. The GroupSpecifier class uses the name (along with any GroupSpecifier properties you've set) to create a string which is the perpetually unique name of the group. To connect another client to the group, that client must use the same group name. For example, if client A uses the group name "firstmesh", other clients that want to communicate with client A must also use the group name "firstmesh". If client B uses the group name "kite", it will connect successfully, but it will create a new group and won't be able to communicate with client A or anyone in the "firstmesh" group.

<?xml version="1.0" encoding="utf-8"?> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" width="100%" height="100%" applicationComplete="OnApplicationComplete()"> <mx:Script> <![CDATA[ private var netConnection:NetConnection = null; private var netStream:NetStream = null; private var netGroup:NetGroup = null; private var video:Video = null; private var sequenceNumber:uint = 0; private var resizeTimer:Timer = null; private const SERVER:String = "rtmfp://fms.example.com/someapp"; [Bindable] private var connected:Boolean = false; [Bindable] private var joinedGroup:Boolean = false; private function OnApplicationComplete():void { userName.text = "user " + int(Math.random() * 65536); groupName.text = "channel" + (int(Math.random() * 899) + 101); resizeTimer = new Timer(2000.0); resizeTimer.addEventListener(TimerEvent.TIMER, DoResizeVideo); resizeTimer.start(); } private function StatusMessage(msg:Object):void { statusLog.text += msg; statusLog.verticalScrollPosition = statusLog.textHeight; statusLog.validateNow(); } private function NetStatusHandler(e:NetStatusEvent):void { StatusMessage(e.info.code); switch(e.info.code) { case "NetConnection.Connect.Success": OnConnect(); break; case "NetConnection.Connect.Closed": case "NetConnection.Connect.Failed": case "NetConnection.Connect.Rejected": case "NetConnection.Connect.AppShutdown": case "NetConnection.Connect.InvalidApp": OnDisconnect(); break; case "NetStream.Connect.Success": // e.info.stream OnNetStreamConnect(); break; case "NetStream.Connect.Rejected": // e.info.stream case "NetStream.Connect.Failed": // e.info.stream DoDisconnect(); break; case "NetGroup.Connect.Success": // e.info.group OnNetGroupConnect(); break; case "NetGroup.Connect.Rejected": // e.info.group case "NetGroup.Connect.Failed": // e.info.group DoDisconnect(); break; case "NetGroup.Posting.Notify": // e.info.message, e.info.messageID OnPosting(e.info.message); break; case "NetStream.MulticastStream.Reset": case "NetStream.Buffer.Full": DoResizeVideo(); break; case "NetGroup.SendTo.Notify": // e.info.message, e.info.from, e.info.fromLocal case "NetGroup.LocalCoverage.Notify": // case "NetGroup.Neighbor.Connect": // e.info.neighbor case "NetGroup.Neighbor.Disconnect": // e.info.neighbor case "NetGroup.MulticastStream.PublishNotify": // e.info.name case "NetGroup.MulticastStream.UnpublishNotify": // e.info.name case "NetGroup.Replication.Fetch.SendNotify": // e.info.index case "NetGroup.Replication.Fetch.Failed": // e.info.index case "NetGroup.Replication.Fetch.Result": // e.info.index, e.info.object case "NetGroup.Replication.Request": // e.info.index, e.info.requestID default: break; } } private function DoConnect():void { StatusMessage("Connecting to \"" + SERVER + "\" ...\n"); netConnection = new NetConnection(); netConnection.addEventListener(NetStatusEvent.NET_STATUS, NetStatusHandler); netConnection.connect(SERVER); } private function OnConnect():void { var groupSpecifier:GroupSpecifier; StatusMessage("Connected\n"); connected = true; groupSpecifier = new GroupSpecifier("max2009lab/" + groupName.text); groupSpecifier.multicastEnabled = true; groupSpecifier.postingEnabled = true; groupSpecifier.serverChannelEnabled = true; netStream = new NetStream(netConnection, groupSpecifier.groupspecWithAuthorizations()); netStream.addEventListener(NetStatusEvent.NET_STATUS, NetStatusHandler); netGroup = new NetGroup(netConnection, groupSpecifier.groupspecWithAuthorizations()); netGroup.addEventListener(NetStatusEvent.NET_STATUS, NetStatusHandler); StatusMessage("Join \"" + groupSpecifier.groupspecWithAuthorizations() + "\"\n"); } private function OnNetStreamConnect():void { netStream.client = this; var mic:Microphone = Microphone.getMicrophone(); if(mic) { mic.codec = SoundCodec.SPEEX; mic.setSilenceLevel(0); netStream.attachAudio(mic); StatusMessage("got microphone\n"); } var camera:Camera = Camera.getCamera(); if(camera) { camera.setMode(320, 240, 10); camera.setQuality(30000, 0); camera.setKeyFrameInterval(15); videoDisplay.attachCamera(camera); videoDisplay.maintainAspectRatio = true; netStream.attachCamera(camera); StatusMessage("got camera\n"); } netStream.publish("stream"); } private function OnNetGroupConnect():void { joinedGroup = true; } private function DoDisconnect():void { if(netConnection) netConnection.close(); videoDisplay.attachCamera(null); } private function OnDisconnect():void { StatusMessage("Disconnected\n"); netConnection = null; netStream = null; netGroup = null; connected = false; joinedGroup = false; } private function ClearChatText():void { chatText.text = ""; } private function DoPost():void { var message:Object = new Object; message.user = userName.text; message.text = chatText.text; message.sequence = sequenceNumber++; message.sender = netConnection.nearID; netGroup.post(message); StatusMessage("==> " + chatText.text + "\n"); chatText.callLater(ClearChatText); } private function OnPosting(message:Object):void { StatusMessage("<" + message.user + "> " + message.text + "\n"); } private function DoResizeVideo(ignored:* = null):void { if(video) { if( (0 == video.videoHeight) || (0 == video.videoWidth) ) { video.height = videoDisplay.height; video.width = videoDisplay.width; video.x = 0; video.y = 0; } else { var videoAspect:Number = Number(video.videoWidth) / Number(video.videoHeight); var displayAspect:Number = Number(videoDisplay.width) / Number(videoDisplay.height); var adjustFactor:Number; if(videoAspect >= displayAspect) // video is wider than display { adjustFactor = Number(video.videoWidth) / Number(videoDisplay.width); video.width = videoDisplay.width; video.height = int(Number(video.videoHeight) / adjustFactor); video.x = 0; video.y = int((videoDisplay.height - video.height) / 2); } else { adjustFactor = Number(video.videoHeight) / Number(videoDisplay.height); video.height = videoDisplay.height; video.width = int(Number(video.videoWidth) / adjustFactor); video.x = int((videoDisplay.width - video.width) / 2); video.y = 0; } } } } public function onPlayStatus(info:Object):void {} public function onMetaData(info:Object):void {} public function onCuePoint(info:Object):void {} public function onTextData(info:Object):void {} public function ValidateConnectAllowed(isConnected:Boolean, groupNameText:String):Boolean { return (!isConnected) && (groupNameText.length > 0); } ]]> </mx:Script> <mx:VBox top="10" right="10" left="10" bottom="10" verticalGap="6"> <mx:HBox width="100%"> <mx:Text text="Group:"/> <mx:TextInput id="groupName" width="100%" text="default" enabled="{!connected}"/> <mx:Button label="Connect" click="DoConnect()" enabled="{ValidateConnectAllowed(connected, groupName.text)}" /> <mx:Button label="Disconnect" click="DoDisconnect()" enabled="{connected}" /> </mx:HBox> <mx:VideoDisplay id="videoDisplay" width="320" height="240" resize="DoResizeVideo()"/> <mx:TextArea id="statusLog" width="100%" height="100%"/> <mx:HBox width="100%"> <mx:TextInput id="userName" width="160" /> <mx:TextInput id="chatText" width="100%" enabled="{joinedGroup}" enter="DoPost()"/> </mx:HBox> </mx:VBox> </mx:Application>
flash.net.GroupSpecifierflash.net.NetStreamflash.events.NetStatusEvent info.code values starting with "NetGroup."netStatus Dispatched when a NetGroup object is reporting its status or error condition.flash.events.NetStatusEvent.NET_STATUSflash.events.NetStatusEvent Dispatched when a NetGroup object is reporting its status or error condition. The netStatus event contains an info property. The info property is an object that contains information about the event, such as whether a connection attempt succeeded or failed. flash.events.NetStatusEvent.infoNetGroup Constructs a NetGroup on the specified NetConnection object and joins it to the group specified by groupspec.The NetConnection instance is not connected. ArgumentErrorArgumentErrorThe groupspec is invalid. ErrorErrorconnectionflash.net:NetConnectionA NetConnection object. groupspecStringA string specifying the RTMFP peer-to-peer group to join, including its name, capabilities, restrictions, and the authorizations of this member. new NetGroup(myConnection, myGroupSpecifier.groupspecWithAuthorizations()); Constructs a new NetGroup on the specified NetConnection object and joins it to the specified group. Constructs a NetGroup on the specified NetConnection object and joins it to the group specified by groupspec.

In most cases, a groupspec has the potential for using the network uplink on the local system. When a NetStream or NetGroup object is constructed with a groupspec, Flash Player displays a Privacy Dialog. The dialog asks whether Flash Player can use the connection to share data with a user's peers. If the user clicks "Allow for this domain", the dialog is not displayed the next time the user connects to this application. If a user does not allow peer-assisted networking, all peer features within the group (posting, directed routing, and object replication, and multicast) are disabled. If permission is allowed, a NetStatusEvent is sent to the NetConnection's event listener with NetGroup.Connect.Success in the code property of the info object. If permission is denied, the code property is NetGroup.Connect.Rejected. Until a NetGroup.Connect.Success event is received, an exception is thrown if you try to call any method of the NetGroup object.

Note: When a client subscribes to a native-IP multicast stream, the security dialog is not displayed.

flash.events.NetStatusEvent.info.code="NetGroup.Connect.Success"flash.events.NetStatusEvent.info.code="NetGroup.Connect.Rejected"flash.net.NetConnectionflash.net.GroupSpecifier
addHaveObjects Adds objects from startIndex through endIndex, to the set of objects this node advertises to neighbors as objects for which it fulfills requests.A number passed to this method is less than 0 or greater than 9007199254740992. RangeErrorRangeErrorstartIndexNumberThe beginning of the range of object indices to add to the Have set. endIndexNumberThe end of the range of object indices to add to the Have set. Adds objects to the set of objects this node advertises to neighbors as objects for which it fulfills requests. Adds objects from startIndex through endIndex, to the set of objects this node advertises to neighbors as objects for which it fulfills requests. By default, the Have set is empty. Indices must be whole numbers from 0 through 9007199254740992.

For more information about object replication, see "Replicate an object within a group" in Flash Media Server Developer’s Guide.

This method sends a NetStatusEvent to the NetGroup's event listener with "NetGroup.Replication.Request" in the code property of the info object.

NOTE: Test for the NetGroup.Neighbor.Connect event before calling this method.

removeHaveObjects()writeRequestedObject()denyRequestedObject()flash.events.NetStatusEvent.info.code="NetGroup.Replication.Request"
addMemberHint Manually adds a record specifying that peerID is a member of the group.TRUE for success, FALSE for failure. BooleanpeerIDStringThe peerID to add to the set of potential neighbors. Manually adds a record specifying that peerID is a member of the group, but doesn't necessarily connect immediately. Manually adds a record specifying that peerID is a member of the group. An immediate connection to it is attempted only if it is needed for the topology. addNeighbor()addNeighbor Manually adds a neighbor by immediately connecting directly to the specified peerID, which must already be in this group.TRUE for success, FALSE for failure. BooleanpeerIDStringThe peerID to which to immediately connect. Manually adds a neighbor by immediately connecting directly to the specified peerID. Manually adds a neighbor by immediately connecting directly to the specified peerID, which must already be in this group. This direct connection may later be dropped if it is not needed for the topology. addMemberHint()addWantObjects Adds objects from startIndex through endIndex, to the set of objects to retrieve.A number passed to this method is less than 0 or greater than 9007199254740992. RangeErrorRangeErrorstartIndexNumberThe beginning of the range of object indices to add to the Want set. endIndexNumberThe end of the range of object indices to add to the Want set. Adds objects to the set of objects to retrieve. Adds objects from startIndex through endIndex, to the set of objects to retrieve. Indices must be whole numbers from 0 through 9007199254740992. By default, the Want set is empty.

For more information about object replication, see "Replicate an object within a group" in Flash Media Server Developer’s Guide.

This method sends a NetStatusEvent to the NetGroup's event listener with NetGroup.Replication.Fetch.SendNotify in the info.code property. This event is followed by an NetGroup.Replication.Fetch.Failed or NetGroup.Replication.Fetch.Result event.

NOTE: Test for the NetGroup.Neighbor.Connect event before calling this method.

removeWantObjects()flash.events.NetStatusEvent.info.code="NetGroup.Replication.Fetch.SendNotify"flash.events.NetStatusEvent.info.code="NetGroup.Replication.Fetch.Failed"flash.events.NetStatusEvent.info.code="NetGroup.Replication.Fetch.Result"
close Disconnect from the group and close this NetGroup. Disconnect from the group and close this NetGroup. This NetGroup is not usable after calling this method. convertPeerIDToGroupAddress Converts a peerID to a group address suitable for use with the sendToNearest() method.The group address for the peerID. StringpeerIDStringThe peerID to convert. Converts a peerID to a group address suitable for use with the sendToNearest() method. Converts a peerID to a group address suitable for use with the sendToNearest() method. flash.net.NetConnection.farIDflash.net.NetConnection.nearIDflash.net.NetStream.farIDsendToNearest()denyRequestedObject Denies a request received in a NetStatusEvent NetGroup.Replication.Request for an object previously advertised with addHaveObjects().requestIDintThe request identifier as given in the NetGroup.Replication.Request event. Denies a request for an object previously advertised. Denies a request received in a NetStatusEvent NetGroup.Replication.Request for an object previously advertised with addHaveObjects(). The requestor can request this object again unless or until it is withdrawn from the Have set.

For more information about object replication, see "Replicate an object within a group" in Flash Media Server Developer’s Guide.

NOTE: Test for the NetGroup.Neighbor.Connect event before calling this method.

addHaveObjects()writeRequestedObject()flash.events.NetStatusEvent.info.code="NetGroup.Replication.Request"
post Sends a message to all members of a group.The messageID of the message if posted, or null on error. The messageID is the hexadecmial of the SHA256 of the raw bytes of the serialization of the message. StringmessageObjectThe message to send to all other members of the group. Sends a message to all members of a group. To call this method, the GroupSpecifier.postingEnabled property must be true in the groupspec passed to the NetGroup constructor. For more information, see "Post messages to a group" in Flash Media Server Developer’s Guide.

All messages must be unique. A message that is identical to one posted earlier might not be propagated. Use a sequence number to make messages unique.

Message delivery is not ordered. Message delivery is not guaranteed.

Messages are serialized in AMF. The message can be one of the following types: an Object, an int, a Number, or a String. The message cannot be a MovieClip.

This method sends a NetStatusEvent to the NetGroup's event listener with "NetGroup.Posting.Notify" in the info.code property. The "NetGroup.Posting.Notify" event is dispatched to the NetGroup on both the client and the server.

NOTE: Test for the NetGroup.Neighbor.Connect event before calling this method.

This is a simple text chat application that uses peer-to-peer networking. The application connects over RTMFP to Flash Media Server. The server keeps the client applications' fingerprints and manages the peer group as clients connect. However, all data is sent between clients (peers) -- data is not sent back to the server.

When you run the application, you can enter any group name into the text input field. The GroupSpecifier class uses the name (along with any GroupSpecifier properties you've set) to create a string which is the perpetually unique name of the group. To connect another client to the group, that client must use the same group name. For example, if client A uses the group name "firstmesh", other clients that want to communicate with client A must also use the group name "firstmesh". If client B uses the group name "kite", it will connect successfully, but it will create a new group and won't be able to communicate with client A or anyone in the "firstmesh" group.

To run this example, add a Button, a Label, a TextInput, and a TextArea component to the Library in Flash Pro.

package { import flash.display.Sprite; import flash.events.TextEvent; import flash.events.MouseEvent; import flash.events.NetStatusEvent; import fl.events.ComponentEvent; import fl.controls.Label; import fl.controls.Button; import fl.controls.TextInput; import fl.controls.TextArea; import flash.text.TextFieldAutoSize; import flash.net.*; public class NetGroupPostExample extends Sprite{ private var connectButton:Button; private var disconnectButton:Button; private var groupNameText:TextInput; private var userNameText:TextInput; private var chatText:TextInput; private var statusLog:TextArea; private var groupLabel:Label; private var userLabel:Label; private var netConnection:NetConnection = null; private var netGroup:NetGroup = null; private var sequenceNumber:uint = 0; private var connected:Boolean = false; private var joinedGroup:Boolean = false; private const SERVER:String = "rtmfp://fms.example.com/someapp"; public function NetGroupPostExample() { DoUI(); } // Writes messages to the TextArea. private function StatusMessage(msg:Object):void{ statusLog.text += msg; statusLog.verticalScrollPosition = statusLog.textHeight; statusLog.validateNow(); } // Handles all NetStatusEvents for the NetConnection and the NetGroup. // This code includes cases it doesn't handle so you can see the cases // and their info objects for learning purposes. private function NetStatusHandler(e:NetStatusEvent):void{ StatusMessage(e.info.code + "\n"); switch(e.info.code){ case "NetConnection.Connect.Success": connectButton.enabled = false; disconnectButton.enabled = true; OnConnect(); break; case "NetConnection.Connect.Closed": OnDisconnect(); break; case "NetGroup.Connect.Success": // e.info.group OnNetGroupConnect(); break; case "NetGroup.Connect.Rejected": // e.info.group case "NetGroup.Connect.Failed": // e.info.group break; case "NetGroup.Posting.Notify": // e.info.message, e.info.messageID OnPosting(e.info.message); break; case "NetStream.MulticastStream.Reset": case "NetStream.Buffer.Full": break; case "NetGroup.SendTo.Notify": // e.info.message, e.info.from, e.info.fromLocal case "NetGroup.LocalCoverage.Notify": // case "NetGroup.Neighbor.Connect": // e.info.neighbor case "NetGroup.Neighbor.Disconnect": // e.info.neighbor case "NetGroup.MulticastStream.PublishNotify": // e.info.name case "NetGroup.MulticastStream.UnpublishNotify": // e.info.name case "NetGroup.Replication.Fetch.SendNotify": // e.info.index case "NetGroup.Replication.Fetch.Failed": // e.info.index case "NetGroup.Replication.Fetch.Result": // e.info.index, e.info.object case "NetGroup.Replication.Request": // e.info.index, e.info.requestID default: break; } } // Creates a NetConnection to Flash Media Server if the app isn't already connected // and if there's a group name in the TextInput field. private function DoConnect(e:MouseEvent):void{ if(!connected && (groupNameText.length > 0)){ StatusMessage("Connecting to \"" + SERVER + "\" ...\n"); netConnection = new NetConnection(); netConnection.addEventListener(NetStatusEvent.NET_STATUS, NetStatusHandler); // To connect to Flash Media Server, pass the server name. netConnection.connect(SERVER); } else { StatusMessage("Enter a group name"); } } // Called in the "NetConnection.Connect.Success" case in the NetStatusEvent handler. private function OnConnect():void{ StatusMessage("Connected\n"); connected = true; // Create a GroupSpecifier object to pass to the NetGroup constructor. // The GroupSpecifier determines the properties of the group var groupSpecifier:GroupSpecifier; groupSpecifier = new GroupSpecifier("aslrexample/" + groupNameText.text); groupSpecifier.postingEnabled = true; groupSpecifier.serverChannelEnabled = true; netGroup = new NetGroup(netConnection, groupSpecifier.groupspecWithAuthorizations()); netGroup.addEventListener(NetStatusEvent.NET_STATUS, NetStatusHandler); StatusMessage("Join \"" + groupSpecifier.groupspecWithAuthorizations() + "\"\n"); } private function OnNetGroupConnect():void{ joinedGroup = true; } private function DoDisconnect(e:MouseEvent):void{ if(netConnection){ netConnection.close(); } } private function OnDisconnect():void{ StatusMessage("Disconnected\n"); netConnection = null; netGroup = null; connected = false; joinedGroup = false; connectButton.enabled = true; disconnectButton.enabled = false; } private function ClearChatText():void{ chatText.text = ""; } // Called when you the chatText field has focus and you press Enter. private function DoPost(e:ComponentEvent):void{ if(joinedGroup){ var message:Object = new Object; message.user = userNameText.text; message.text = chatText.text; message.sequence = sequenceNumber++; message.sender = netConnection.nearID; netGroup.post(message); StatusMessage("==> " + chatText.text + "\n"); } else { StatusMessage("Click Connect before sending a chat message"); } ClearChatText(); } private function OnPosting(message:Object):void{ StatusMessage("<" + message.user + "> " + message.text + "\n"); } private function DoUI():void { groupLabel = new Label(); groupLabel.move(20, 10); groupLabel.autoSize = TextFieldAutoSize.LEFT groupLabel.text = "Group name:" addChild(groupLabel); groupNameText = new TextInput(); groupNameText.move(90, 10); groupNameText.text = "channel" + (int(Math.random() * 899) + 101); addChild(groupNameText); connectButton = new Button(); connectButton.addEventListener(MouseEvent.CLICK, DoConnect); connectButton.move(205, 10); connectButton.label = "Connect"; addChild(connectButton); disconnectButton = new Button(); disconnectButton.addEventListener(MouseEvent.CLICK, DoDisconnect); disconnectButton.move(310, 10); disconnectButton.label = "Disconnect"; disconnectButton.enabled = false; addChild(disconnectButton); statusLog = new TextArea(); statusLog.move(30, 38); statusLog.width = 360; statusLog.height = 215; statusLog.editable = false; addChild(statusLog); userLabel = new Label(); userLabel.move(20, 270); userLabel.autoSize = TextFieldAutoSize.LEFT userLabel.text = "User name:" addChild(userLabel); userNameText = new TextInput(); userNameText.move(80, 270); userNameText.text = "user " + int(Math.random() * 65536); addChild(userNameText); chatText = new TextInput(); chatText.addEventListener(ComponentEvent.ENTER, DoPost); chatText.move(185, 270); chatText.maxChars = 255; chatText.width = 215; addChild(chatText); } public function onPlayStatus(info:Object):void {} public function onMetaData(info:Object):void {} public function onCuePoint(info:Object):void {} public function onTextData(info:Object):void {} } }
flash.events.NetStatusEvent.info.code="NetGroup.Posting.Notify"
removeHaveObjects Removes objects from startIndex through endIndex, from the set of objects this node advertises to neighbors as objects for which it fulfills requests.A number passed to this method is less than 0 or greater than 9007199254740992. RangeErrorRangeErrorstartIndexNumberThe beginning of the range of object indices to remove from the Have set. endIndexNumberThe end of the range of object indices to remove from the Have set. Removes objects from the set of objects this node advertises to neighbors as objects for which it fulfills requests. Removes objects from startIndex through endIndex, from the set of objects this node advertises to neighbors as objects for which it fulfills requests. Indices must be whole numbers from 0 through 9007199254740992.

For more information about object replication, see "Replicate an object within a group" in Flash Media Server Developer’s Guide.

NOTE: Test for the NetGroup.Neighbor.Connect event before calling this method.

addHaveObjects()
removeWantObjects Removes objects from startIndex through endIndex, from the set of objects to retrieve.A number passed to this method is less than 0 or greater than 9007199254740992. RangeErrorRangeErrorstartIndexNumberThe beginning of the range of object indices to remove from the Want set. endIndexNumberThe end of the range of object indices to remove from the Want set. Removes objects from the set of objects to retrieve. Removes objects from startIndex through endIndex, from the set of objects to retrieve. Indices must be whole numbers from 0 through 9007199254740992.

For more information about object replication, see "Replicate an object within a group" in Flash Media Server Developer’s Guide.

NOTE: Test for the NetGroup.Neighbor.Connect event before calling this method.

addWantObjects()
sendToAllNeighbors Sends a message to all neighbors.A property of enumeration class NetGroupSendResult indicating the success or failure of the send. StringmessageObjectThe message to send. Sends a message to all neighbors. Returns NetGroupSendResult.SENT if at least one neighbor was selected.

For more information about routing messages, see "Route messages directly to a peer" in Flash Media Server Developer’s Guide.

When a node receives a message, a NetStatusEvent is sent to the NetGroup's event listener with NetGroup.SendTo.Notify in the code property of the info object.

NOTE: Test for the NetGroup.Neighbor.Connect event before calling this method.

sendToNeighbor()flash.events.NetStatusEvent.info.code="NetGroup.SendTo.Notify"flash.net.NetGroupSendResult
sendToNearest Sends a message to the neighbor (or local node) nearest to the specified group address.A property of enumeration class NetGroupSendResult indicating the success or failure of the send. StringmessageObjectThe message to send. groupAddressStringThe group address toward which to route the message. Sends a message to the neighbor (or local node) nearest to the specified group address. Considers neighbors from the entire ring. Returns NetGroupSendResult.SENT if the message was successfully sent toward its destination.

For more information about routing messages, see "Route messages directly to a peer" in Flash Media Server Developer’s Guide.

When a node receives a message, a NetStatusEvent is sent to the NetGroup's event listener with NetGroup.SendTo.Notify in the code property of the info object.

NOTE: Test for the NetGroup.Neighbor.Connect event before calling this method.

convertPeerIDToGroupAddress()receiveModeflash.net.NetGroupSendResultflash.events.NetStatusEvent.info.code="NetGroup.SendTo.Notify"
sendToNeighbor Sends a message to the neighbor specified by the sendMode parameter.A property of enumeration class NetGroupSendResult indicating the success or failure of the send. StringmessageObjectThe message to send. sendModeStringA property of enumeration class NetGroupSendMode specifying the neighbor to which to send the message. Sends message to the neighbor specified by the sendMode parameter. Sends a message to the neighbor specified by the sendMode parameter. Returns NetGroupSendResult.SENT if the message was successfully sent to the requested destination.

For more information about routing messages, see "Route messages directly to a peer" in Flash Media Server Developer’s Guide.

When a node receives a message, a NetStatusEvent is sent to the NetGroup's event listener with NetGroup.SendTo.Notify in the code property of the info object.

NOTE: Test for the NetGroup.Neighbor.Connect event before calling this method.

sendToAllNeighbors()flash.events.NetStatusEvent.info.code="NetGroup.SendTo.Notify"flash.net.NetGroupSendModeflash.net.NetGroupSendResult
writeRequestedObject Satisfies the request as received by NetStatusEvent NetGroup.Replication.Request for an object previously advertised with the addHaveObjects() method.requestIDintThe request identifier as given in the NetGroup.Replication.Request event. objectObjectThe object corresponding to the index given in the NetGroup.Replication.Request event. Satisfies the request for an object that was previously advertised. Satisfies the request as received by NetStatusEvent NetGroup.Replication.Request for an object previously advertised with the addHaveObjects() method. The object can be any of the following: An Object, an int, a Number, and a String. The object cannot be a MovieClip.

For more information about object replication, see "Replicate an object within a group" in Flash Media Server Developer’s Guide.

NOTE: Test for the NetGroup.Neighbor.Connect event before calling this method.

addHaveObjects()denyRequestedObject()flash.events.NetStatusEvent.info.code="NetGroup.Replication.Request"
estimatedMemberCount Specifies the estimated number of members of the group, based on local neighbor density and assuming an even distribution of group addresses.NumberSpecifies the estimated number of members of the group. Specifies the estimated number of members of the group, based on local neighbor density and assuming an even distribution of group addresses. neighborCountinfo Returns a NetGroupInfo object whose properties provide Quality of Service statistics about this NetGroup's RTMFP peer-to-peer data transport.flash.net:NetGroupInfoReturns a NetGroupInfo object whose properties provide Quality of Service statistics. Returns a NetGroupInfo object whose properties provide Quality of Service statistics about this NetGroup's RTMFP peer-to-peer data transport. flash.net.NetGroupInfolocalCoverageFrom Specifies the start of the range of group addresses for which this node is the "nearest" and responsible.String Specifies the start of the range of group addresses for which this node is the "nearest" and responsible. The range is specified in the increasing direction along the group address ring mod 2256. localCoverageToreceiveModesendToNearest()flash.events.NetStatusEvent.info.code="NetGroup.LocalCoverage.Notify"localCoverageTo Specifies the end of the range of group addresses for which this node is the "nearest" and responsible.String Specifies the end of the range of group addresses for which this node is the "nearest" and responsible. The range is specified in the increasing direction along the group address ring mod 2256. localCoverageFromreceiveModesendToNearest()flash.events.NetStatusEvent.info.code="NetGroup.LocalCoverage.Notify"neighborCount Specifies the number of group members to which this node is directly connected.NumberSpecifies the number of group members to which this node is directly connected. Specifies the number of group members to which this node is directly connected. addNeighbor()estimatedMemberCountflash.events.NetStatusEvent.info.code="NetGroup.Neighbor.Connect"flash.events.NetStatusEvent.info.code="NetGroup.Neighbor.Disconnect"receiveMode Specifies this node's routing receive mode as one of values in the NetGroupReceiveMode enum class.String Specifies this node's routing receive mode as one of values in the NetGroupReceiveMode enum class. localCoverageFromlocalCoverageTosendToNearest()flash.net.NetGroupReceiveModereplicationStrategy Specifies the object replication fetch strategy.String Specifies the object replication fetch strategy. The value is one of the enumerated values in the NetGroupReplicationStrategy class. flash.net.NetGroupReplicationStrategy
getClassByAlias Looks up a class that previously had an alias registered through a call to the registerClassAlias() method.The alias was not registered. ReferenceErrorReferenceErrorThe class associated with the given alias. If not found, an exception will be thrown. ClassaliasNameStringThe alias to find. Looks up a class that previously had an alias registered through a call to the registerClassAlias() method.

This method does not interact with the flash.utils.getDefinitionByName() method.

registerClassAlias()
navigateToURL Opens or replaces a window in the application that contains the Flash Player container (usually a browser).The digest property of the request object is not null. You should only set the digest property of a URLRequest object for use calling the URLLoader.load() method when loading a SWZ file (an Adobe platform component). IOErrorflash.errors:IOErrorIn Flash Player (and in non-application sandbox content in Adobe AIR), this error is thrown in the following situations:
  • Local untrusted SWF files may not communicate with the Internet. You can avoid this situation by reclassifying this SWF file as local-with-networking or trusted.
  • A navigate operation attempted to evaluate a scripting pseudo-URL, but the containing document (usually an HTML document in a browser) is from a sandbox to which you do not have access. You can avoid this situation by specifying allowScriptAccess="always" in the containing document.
  • You cannot navigate the special windows "_self", "_top", or "_parent" if your SWF file is contained by an HTML page that has set the allowScriptAccess to "none", or to "sameDomain" when the domains of the HTML file and the SWF file do not match.
  • You cannot navigate a window with a nondefault name from within a SWF file that is in the local-with-filesystem sandbox.
  • You cannot connect to commonly reserved ports. For a complete list of blocked ports, see "Restricting Networking APIs" in the ActionScript 3.0 Developer's Guide.
SecurityErrorSecurityError
If the method is not called in response to a user action, such as a mouse event or keypress event. This requirement only applies to content in Flash Player and to non-application sandbox content in Adobe AIR. ErrorErrorrequestflash.net:URLRequestA URLRequest object that specifies the URL to navigate to.

For content running in Adobe AIR, when using the navigateToURL() function, the runtime treats a URLRequest that uses the POST method (one that has its method property set to URLRequestMethod.POST) as using the GET method.

windowStringnullThe browser window or HTML frame in which to display the document indicated by the request parameter. You can enter the name of a specific window or use one of the following values:
  • "_self" specifies the current frame in the current window.
  • "_blank" specifies a new window.
  • "_parent" specifies the parent of the current frame.
  • "_top" specifies the top-level frame in the current window.

If you do not specify a value for this parameter, a new empty window is created. In the stand-alone player, you can either specify a new ("_blank") window or a named window. The other values don't apply.

Note: When code in a SWF file that is running in the local-with-filesystem sandbox calls the navigateToURL() function and specifies a custom window name for the window parameter, the window name is transfered into a random name. The name is in the form "_flashXXXXXXXX", where each X represents a random hexadecimal digit. Within the same session (until you close the containing browser window), if you call the function again and specify the same name for the window parameter, the same random string is used.

Opens or replaces a window in the application that contains the Flash Player container (usually a browser). In Adobe AIR, the function opens a URL in the default system web browser

Important Security Note

Developers often pass URL values to the navigateToURL() function that were obtained from external sources such as FlashVars. Attackers may try to manipulate these external sources to perform attacks such as cross-site scripting. Therefore, developers should validate all URLs before passing them to this function.

Good data validation for URLs can mean different things depending on the usage of the URL within the overall application. The most common data validation techniques include validating that the URL is of the appropriate scheme. For instance, unintentionally allowing javascript: URLs may result in cross-site scripting. Validating that the URL is a within your domain can ensure that the SWF file can't be used as an open-redirector by people who conduct phishing attacks. For additional security, you may also choose to validate the path of the URL and to validate that the URL conforms to the RFC guidelines

For example, the following code shows a simple example of performing data validation by denying any URL that does not begin with http:// or https:// and validating that the URL is within your domain name. This example may not be appropriate for all web applications and you should consider whether additional checks against the URL are necessary.

// AS3 Regular expression pattern match for URLs that start with http:// and https:// plus your domain name. function checkProtocol (flashVarURL:String):Boolean { // Get the domain name for the SWF if it is not known at compile time. // If the domain is known at compile time, then the following two lines can be replaced with a hard coded string. var my_lc:LocalConnection = new LocalConnection(); var domainName:String = my_lc.domain; // Build the RegEx to test the URL. // This RegEx assumes that there is at least one "/" after the // domain. http://www.mysite.com will not match. var pattern:RegExp = new RegExp("^http[s]?\:\\/\\/([^\\/]+)\\/"); var result:Object = pattern.exec(flashVarURL); if (result == null || result[1] != domainName || flashVarURL.length >= 4096) { return (false); } return (true); }

For local content running in a browser, calls to the navigateToURL() method that specify a "javascript:" pseudo-protocol (via a URLRequest object passed as the first parameter) are only permitted if the SWF file and the containing web page (if there is one) are in the local-trusted security sandbox. Some browsers do not support using the javascript protocol with the navigateToURL() method. Instead, consider using the call() method of the ExternalInterface API to invoke JavaScript methods within the enclosing HTML page.

In Flash Player, and in non-application sandboxes in Adobe AIR, you cannot connect to commonly reserved ports. For a complete list of blocked ports, see "Restricting Networking APIs" in the ActionScript 3.0 Developer's Guide.

In Flash Player 10 and later running in a browser, using this method programmatically to open a pop-up window may not be successful. Various browsers (and browser configurations) may block pop-up windows at any time; it is not possible to guarantee any pop-up window will appear. However, for the best chance of success, use this method to open a pop-up window only in code that executes as a direct result of a user action (for example, in an event handler for a mouse click or key-press event.)

In Flash Player 10 and later, if you use a multipart Content-Type (for example "multipart/form-data") that contains an upload (indicated by a "filename" parameter in a "content-disposition" header within the POST body), the POST operation is subject to the security rules applied to uploads:

  • The POST operation must be performed in response to a user-initiated action, such as a mouse click or key press.
  • If the POST operation is cross-domain (the POST target is not on the same server as the SWF file that is sending the POST request), the target server must provide a URL policy file that permits cross-domain access.

Also, for any multipart Content-Type, the syntax must be valid (according to the RFC2046 standards). If the syntax appears to be invalid, the POST operation is subject to the security rules applied to uploads.

In AIR, on mobile platforms, the sms: and tel: URI schemes are supported. On Android, vipaccess:, connectpro:, and market: URI schemes are supported. The URL syntax is subject to the platform conventions. For example, on Android, the URI scheme must be lower case. When you navigate to a URL using one of these schemes, the runtime opens the URL in the default application for handling the scheme. Thus, navigating to tel:+5555555555 opens the phone dialer with the specified number already entered. A separate application or utility, such as a phone dialer must be available to process the URL.

The following code shows how you can invoke the VIP Access and Connect Pro applications on Android:

//Invoke the VIP Access Application. navigateToURL(new URLRequest("vipaccess://com.verisign.mvip.main?action=securitycode")); //Invoke the Connect Pro Application. navigateToURL(new URLRequest("connectpro://"));
The following example opens the URL http://www.adobe.com in a new browser window and passes data about a user session, captured in a URLVariables object, to the web server. package { import flash.display.Sprite; import flash.net.navigateToURL; import flash.net.URLRequest; import flash.net.URLVariables; public class NavigateToURLExample extends Sprite { public function NavigateToURLExample() { var url:String = "http://www.adobe.com"; var variables:URLVariables = new URLVariables(); variables.exampleSessionId = new Date().getTime(); variables.exampleUserLabel = "Your Name"; var request:URLRequest = new URLRequest(url); request.data = variables; try { navigateToURL(request); } catch (e:Error) { // handle error here } } } } The following example shows how you can open new browser windows from Flash Player using the navigateToURL() method. Example provided by ActionScriptExamples.com. // Requires // - Button symbol on Stage (or a display object, such as a MovieClip) with instance name "buttonSymbol" // buttonSymbol.addEventListener(MouseEvent.CLICK, buttonSymbol_click); function buttonSymbol_click(evt:MouseEvent):void { var req:URLRequest = new URLRequest("http://www.adobe.com/"); navigateToURL(req, "_blank"); } The following example illustrates the syntax for launching the device telephone dialer with a specified number. var request:URLRequest = new URLRequest( "tel:+5555555555" ); navigateToURL( request ); The following example illustrates the syntax for launching the device text message application with a specified receipient. var request:URLRequest = new URLRequest( "sms:+5555555555" ); navigateToURL( request ); The following example illustrates the syntax for launching the Android Market app. The search parameter is set to find the Flash Player app. var request:URLRequest = new URLRequest( "market://search?q=pname:com.adobe.flashplayer" ); navigateToURL( request );
flash.external.ExternalInterface.call()
registerClassAlias Preserves the class (type) of an object when the object is encoded in Action Message Format (AMF).If either parameter is null. TypeErrorTypeErroraliasNameStringThe alias to use. classObjectClassThe class associated with the given alias. Preserves the class (type) of an object when the object is encoded in Action Message Format (AMF). When you encode an object into AMF, this function saves the alias for its class, so that you can recover the class when decoding the object. If the encoding context did not register an alias for an object's class, the object is encoded as an anonymous object. Similarly, if the decoding context does not have the same alias registered, an anonymous object is created for the decoded data.

LocalConnection, ByteArray, SharedObject, NetConnection and NetStream are all examples of classes that encode objects in AMF.

The encoding and decoding contexts do not need to use the same class for an alias; they can intentionally change classes, provided that the destination class contains all of the members that the source class serializes.

This example uses the registerClassAlias() function to register an alias (com.example.eg) for the class ExampleClass. Because an alias is registered for the class, the object is able to be deserialized as an instance of ExampleClass, and the code outputs true. If the registerClassAlias() call were removed, the code would output false. package { import flash.display.Sprite; import flash.net.registerClassAlias; import flash.utils.ByteArray; public class RegisterClassAliasExample extends Sprite { public function RegisterClassAliasExample() { registerClassAlias("com.example.eg", ExampleClass); var eg1:ExampleClass = new ExampleClass(); var ba:ByteArray = new ByteArray(); ba.writeObject(eg1); ba.position = 0; var eg2:* = ba.readObject(); trace(eg2 is ExampleClass); // true } } } class ExampleClass {}
ObjectEncoding class
sendToURL Sends a URL request to a server, but ignores any response.Local untrusted SWF files cannot communicate with the Internet. You can avoid this situation by reclassifying this SWF file as local-with-networking or trusted. SecurityErrorSecurityErrorYou cannot connect to commonly reserved ports. For a complete list of blocked ports, see "Restricting Networking APIs" in the ActionScript 3.0 Developer's Guide. SecurityErrorSecurityErrorrequestflash.net:URLRequestA URLRequest object specifying the URL to send data to. Sends a URL request to a server, but ignores any response.

To examine the server response, use the URLLoader.load() method instead.

You cannot connect to commonly reserved ports. For a complete list of blocked ports, see "Restricting Networking APIs" in the ActionScript 3.0 Developer's Guide.

You can prevent a SWF file from using this method by setting the allowNetworking parameter of the the object and embed tags in the HTML page that contains the SWF content.

In Flash Player 10 and later, if you use a multipart Content-Type (for example "multipart/form-data") that contains an upload (indicated by a "filename" parameter in a "content-disposition" header within the POST body), the POST operation is subject to the security rules applied to uploads:

  • The POST operation must be performed in response to a user-initiated action, such as a mouse click or key press.
  • If the POST operation is cross-domain (the POST target is not on the same server as the SWF file that is sending the POST request), the target server must provide a URL policy file that permits cross-domain access.

Also, for any multipart Content-Type, the syntax must be valid (according to the RFC2046 standards). If the syntax appears to be invalid, the POST operation is subject to the security rules applied to uploads.

For more information related to security, see the Flash Player Developer Center Topic: Security.

The following example passes data about a user session, captured in a URLVariables object, to the application at http://www.yourDomain.com/application.jsp. package { import flash.display.Sprite; import flash.net.URLRequest; import flash.net.URLVariables; import flash.net.sendToURL; public class SendToURLExample extends Sprite { public function SendToURLExample() { var url:String = "http://www.yourDomain.com/application.jsp"; var variables:URLVariables = new URLVariables(); variables.sessionId = new Date().getTime(); variables.userLabel = "Your Name"; var request:URLRequest = new URLRequest(url); request.data = variables; trace("sendToURL: " + request.url + "?" + request.data); try { sendToURL(request); } catch (e:Error) { // handle error here } } } }
NetGroupReceiveMode The NetGroupReceiveMode class is an enumeration of constant values used for the receiveMode property of the NetGroup class.An enumeration of constant values used for the receiveMode property of the NetGroup class. Object The NetGroupReceiveMode class is an enumeration of constant values used for the receiveMode property of the NetGroup class. flash.net.NetGroup.receiveModeflash.net.NetGroup.sendToNearest()EXACT Specifies that this node accepts local messages from neighbors only if the address the neighbor uses matches this node's address exactly.exactString Specifies that this node accepts local messages from neighbors only if the address the neighbor uses matches this node's address exactly. That is, this node considers itself as nearest for any NetGroup.sendToNearest() call only if the groupAddress parameter passed to NetGroup.sendToNearest() matches this node's group address exactly. This value is the default setting.

If you want to enable distributed routing behavior, set this value to NetGroupReceiveMode.NEAREST. With this value set, a node waits for its connectivity to stabilize before participating in the Directed Routing mesh.

flash.net.NetGroup.sendToNearest()
NEAREST Specifies that this node accepts local messages from neighbors that send messages to group addresses that don't match this node's address exactly.nearestString Specifies that this node accepts local messages from neighbors that send messages to group addresses that don't match this node's address exactly. Messages are received when this node is nearest among all neighbors whose receive mode is NetGroupReceiveMode.NEAREST. Distance is measured between addresses on the ring mod 2256. flash.net.NetGroup.sendToNearest()
Responder The Responder class provides an object that is used in NetConnection.call() to handle return values from the server related to the success or failure of specific operations.Object The Responder class provides an object that is used in NetConnection.call() to handle return values from the server related to the success or failure of specific operations. When working with NetConnection.call(), you may encounter a network operation fault specific to the current operation or a fault related to the current connection status. Operation errors target the Responder object instead of the NetConnection object for easier error handling. NetConnection.call()Responder Creates a new Responder object.resultFunctionThe function invoked if the call to the server succeeds and returns a result. statusFunctionnullThe function invoked if the server returns an error. Creates a new Responder object. You pass a Responder object to NetConnection.call() to handle return values from the server. You may pass null for either or both parameters. URLRequestHeader A URLRequestHeader object encapsulates a single HTTP request header and consists of a name/value pair.Object A URLRequestHeader object encapsulates a single HTTP request header and consists of a name/value pair. URLRequestHeader objects are used in the requestHeaders property of the URLRequest class.

In Adobe® AIR®, content in the application security sandbox (such as content installed with the AIR application) can use any request headers, without error. However, for content running in Adobe AIR that is in a different security sandbox, or for content running in Flash® Player, using following request headers cause a runtime error to be thrown, and the restricted terms are not case-sensitive (for example, Get, get, and GET are each not allowed):

In Flash Player and in Adobe AIR content outside of the application security sandbox, the following request headers cannot be used, and the restricted terms are not case-sensitive (for example, Get, get, and GET are all not allowed). Also, hyphenated terms apply if an underscore character is used (for example, both Content-Length and Content_Length are not allowed):

Accept-Charset, Accept-Encoding, Accept-Ranges, Age, Allow, Allowed, Authorization, Charge-To, Connect, Connection, Content-Length, Content-Location, Content-Range, Cookie, Date, Delete, ETag, Expect, Get, Head, Host, If-Modified-Since, Keep-Alive, Last-Modified, Location, Max-Forwards, Options, Origin, Post, Proxy-Authenticate, Proxy-Authorization, Proxy-Connection, Public, Put, Range, Referer, Request-Range, Retry-After, Server, TE, Trace, Trailer, Transfer-Encoding, Upgrade, URI, User-Agent, Vary, Via, Warning, WWW-Authenticate, x-flash-version.

URLRequestHeader objects are restricted in length. If the cumulative length of a URLRequestHeader object (the length of the name property plus the value property) or an array of URLRequestHeader objects used in the URLRequest.requestHeaders property exceeds the acceptable length, an exception is thrown.

Content running in Adobe AIR sets the ACCEPT header to the following, unless you specify a setting for the ACCEPT header in the requestHeaders property of the URLRequest class:

text/xml, application/xml, application/xhtml+xml, text/html;q=0.9, text/plain;q=0.8, image/png, application/x-shockwave-flash, video/mp4;q=0.9, flv-application/octet-stream;q=0.8, video/x-flv;q=0.7, audio/mp4, ~~/~~;q=0.5

Not all methods that accept URLRequest parameters support the requestHeaders property, consult the documentation for the method you are calling. For example, the FileReference.upload() and FileReference.download() methods do not support the URLRequest.requestHeaders property.

Due to browser limitations, custom HTTP request headers are only supported for POST requests, not for GET requests.

The following example adds a single HTTP request header header to the array for the requestHeaders property. The header indicates that the application should forward the request to the origin server even if it has a cached copy of what is being requested. package { import flash.display.Sprite; import flash.events.*; import flash.net.URLLoader; import flash.net.URLRequest; import flash.net.URLRequestHeader; import flash.net.URLRequestMethod; import flash.net.URLVariables; public class URLRequestHeaderExample extends Sprite { public function URLRequestHeaderExample() { var loader:URLLoader = new URLLoader(); configureListeners(loader); var header:URLRequestHeader = new URLRequestHeader("pragma", "no-cache"); var request:URLRequest = new URLRequest("http://www.[yourdomain].com/greeting.cfm"); request.data = new URLVariables("name=John+Doe"); request.method = URLRequestMethod.POST; request.requestHeaders.push(header); try { loader.load(request); } catch (error:Error) { trace("Unable to load requested document."); } } private function configureListeners(dispatcher:IEventDispatcher):void { dispatcher.addEventListener(Event.COMPLETE, completeHandler); dispatcher.addEventListener(Event.OPEN, openHandler); dispatcher.addEventListener(ProgressEvent.PROGRESS, progressHandler); dispatcher.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler); dispatcher.addEventListener(HTTPStatusEvent.HTTP_STATUS, httpStatusHandler); dispatcher.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler); } private function completeHandler(event:Event):void { var loader:URLLoader = URLLoader(event.target); trace("completeHandler: " + loader.data); } private function openHandler(event:Event):void { trace("openHandler: " + event); } private function progressHandler(event:ProgressEvent):void { trace("progressHandler loaded:" + event.bytesLoaded + " total: " + event.bytesTotal); } private function securityErrorHandler(event:SecurityErrorEvent):void { trace("securityErrorHandler: " + event); } private function httpStatusHandler(event:HTTPStatusEvent):void { trace("httpStatusHandler: " + event); } private function ioErrorHandler(event:IOErrorEvent):void { trace("ioErrorHandler: " + event); } } }
URLRequestURLLoaderURLRequestHeader Creates a new URLRequestHeader object that encapsulates a single HTTP request header.nameStringAn HTTP request header name (such as Content-Type or SOAPAction). valueStringThe value associated with the name property (such as text/plain). Creates a new URLRequestHeader object that encapsulates a single HTTP request header. URLRequestHeader objects are used in the requestHeaders property of the URLRequest class. name An HTTP request header name (such as Content-Type or SOAPAction).String An HTTP request header name (such as Content-Type or SOAPAction). value The value associated with the name property (such as text/plain).String The value associated with the name property (such as text/plain).
URLRequestMethod The URLRequestMethod class provides values that specify whether the URLRequest object should use the POST method or the GET method when sending data to a server.Object The URLRequestMethod class provides values that specify whether the URLRequest object should use the POST method or the GET method when sending data to a server. The following example loads and displays the data found in a local text file. It also traces event handling information.

Note:To run this example, put a file named example.txt in the same directory as your SWF file. That file should be a simple text file containing a few words or lines of text.

The example code does the following:

  1. The constructor function creates a URLLoader instance named loader.
  2. The loader object is passed to the configureListeners() method, which adds listeners for each of the supported URLLoader events.
  3. A URLRequest instance named request is created, which specifies name of the file to be loaded.
  4. The method property of the request is set to URLRequestMethod.POST.
  5. The request object is then passed to loader.load(), which loads the text file.
  6. When the URLLoader has finished loading the text file the Event.COMPLETE event fires, triggering the completeHandler() method. The completeHandler() method simply traces the data property, the contents of the text file.
package { import flash.display.Sprite; import flash.events.*; import flash.net.*; public class URLRequestMethodExample extends Sprite { public function URLRequestMethodExample() { var loader:URLLoader = new URLLoader(); configureListeners(loader); var request:URLRequest = new URLRequest("example.txt"); request.method = URLRequestMethod.POST; loader.load(request); } private function configureListeners(dispatcher:IEventDispatcher):void { dispatcher.addEventListener(Event.COMPLETE, completeHandler); dispatcher.addEventListener(Event.OPEN, openHandler); dispatcher.addEventListener(ProgressEvent.PROGRESS, progressHandler); dispatcher.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler); dispatcher.addEventListener(HTTPStatusEvent.HTTP_STATUS, httpStatusHandler); dispatcher.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler); } private function completeHandler(event:Event):void { var loader:URLLoader = URLLoader(event.target); trace("completeHandler: " + loader.data); } private function openHandler(event:Event):void { trace("openHandler: " + event); } private function progressHandler(event:ProgressEvent):void { trace("progressHandler loaded:" + event.bytesLoaded + " total: " + event.bytesTotal); } private function securityErrorHandler(event:SecurityErrorEvent):void { trace("securityErrorHandler: " + event); } private function httpStatusHandler(event:HTTPStatusEvent):void { trace("httpStatusHandler: " + event); } private function ioErrorHandler(event:IOErrorEvent):void { trace("ioErrorHandler: " + event); } } }
URLRequestURLVariablesDELETE Specifies that the URLRequest object is a DELETE.DELETEStringSpecifies that the URLRequest object is a DELETE. Specifies that the URLRequest object is a DELETE. GET Specifies that the URLRequest object is a GET.GETStringSpecifies that the URLRequest object is a GET. Specifies that the URLRequest object is a GET. HEAD Specifies that the URLRequest object is a HEAD.HEADStringSpecifies that the URLRequest object is a HEAD. Specifies that the URLRequest object is a HEAD. OPTIONS Specifies that the URLRequest object is OPTIONS.OPTIONSStringSpecifies that the URLRequest object is OPTIONS. Specifies that the URLRequest object is OPTIONS. POST Specifies that the URLRequest object is a POST.POSTStringSpecifies that the URLRequest object is a POST. Specifies that the URLRequest object is a POST.

Note: For content running in Adobe AIR, when using the navigateToURL() function, the runtime treats a URLRequest that uses the POST method (one that has its method property set to URLRequestMethod.POST) as using the GET method.

PUT Specifies that the URLRequest object is a PUT.PUTStringSpecifies that the URLRequest object is a PUT. Specifies that the URLRequest object is a PUT.
FileReference The FileReference class provides a means to upload and download files between a user's computer and a server.flash.events:EventDispatcher The FileReference class provides a means to upload and download files between a user's computer and a server. An operating-system dialog box prompts the user to select a file to upload or a location for download. Each FileReference object refers to a single file on the user's disk and has properties that contain information about the file's size, type, name, creation date, modification date, and creator type (Macintosh only).

Note: In Adobe AIR, the File class, which extends the FileReference class, provides more capabilities and has less security restrictions than the FileReference class.

FileReference instances are created in the following ways:

  • When you use the new operator with the FileReference constructor: var myFileReference = new FileReference();
  • When you call the FileReferenceList.browse() method, which creates an array of FileReference objects.

During an upload operation, all the properties of a FileReference object are populated by calls to the FileReference.browse() or FileReferenceList.browse() methods. During a download operation, the name property is populated when the select event is dispatched; all other properties are populated when the complete event is dispatched.

The browse() method opens an operating-system dialog box that prompts the user to select a file for upload. The FileReference.browse() method lets the user select a single file; the FileReferenceList.browse() method lets the user select multiple files. After a successful call to the browse() method, call the FileReference.upload() method to upload one file at a time. The FileReference.download() method prompts the user for a location to save the file and initiates downloading from a remote URL.

The FileReference and FileReferenceList classes do not let you set the default file location for the dialog box that the browse() or download() methods generate. The default location shown in the dialog box is the most recently browsed folder, if that location can be determined, or the desktop. The classes do not allow you to read from or write to the transferred file. They do not allow the SWF file that initiated the upload or download to access the uploaded or downloaded file or the file's location on the user's disk.

The FileReference and FileReferenceList classes also do not provide methods for authentication. With servers that require authentication, you can download files with the Flash® Player browser plug-in, but uploading (on all players) and downloading (on the stand-alone or external player) fails. Listen for FileReference events to determine whether operations complete successfully and to handle errors.

For content running in Flash Player or for content running in Adobe AIR outside of the application security sandbox, uploading and downloading operations can access files only within its own domain and within any domains that a URL policy file specifies. Put a policy file on the file server if the content initiating the upload or download doesn't come from the same domain as the file server.

Note that because of new functionality added to the Flash Player, when publishing to Flash Player 10, you can have only one of the following operations active at one time: FileReference.browse(), FileReference.upload(), FileReference.download(), FileReference.load(), FileReference.save(). Otherwise, Flash Player throws a runtime error (code 2174). Use FileReference.cancel() to stop an operation in progress. This restriction applies only to Flash Player 10. Previous versions of Flash Player are unaffected by this restriction on simultaneous multiple operations.

While calls to the FileReference.browse(), FileReferenceList.browse(), or FileReference.download() methods are executing, SWF file playback pauses in stand-alone and external versions of Flash Player and in AIR for Linux and Mac OS X 10.1 and earlier

The following sample HTTP POST request is sent from Flash Player to a server-side script if no parameters are specified:

  POST /handler.cfm HTTP/1.1 
  Accept: text/~~
  Content-Type: multipart/form-data; 
  boundary=----------Ij5ae0ae0KM7GI3KM7 
  User-Agent: Shockwave Flash 
  Host: www.example.com 
  Content-Length: 421 
  Connection: Keep-Alive 
  Cache-Control: no-cache
  
  ------------Ij5GI3GI3ei4GI3ei4KM7GI3KM7KM7
  Content-Disposition: form-data; name="Filename"
  
  MyFile.jpg
  ------------Ij5GI3GI3ei4GI3ei4KM7GI3KM7KM7
  Content-Disposition: form-data; name="Filedata"; filename="MyFile.jpg"
  Content-Type: application/octet-stream
  
  FileDataHere
  ------------Ij5GI3GI3ei4GI3ei4KM7GI3KM7KM7
  Content-Disposition: form-data; name="Upload"
  
  Submit Query
  ------------Ij5GI3GI3ei4GI3ei4KM7GI3KM7KM7--
  

Flash Player sends the following HTTP POST request if the user specifies the parameters "api_sig", "api_key", and "auth_token":

  POST /handler.cfm HTTP/1.1 
  Accept: text/~~
  Content-Type: multipart/form-data; 
  boundary=----------Ij5ae0ae0KM7GI3KM7 
  User-Agent: Shockwave Flash 
  Host: www.example.com 
  Content-Length: 421 
  Connection: Keep-Alive 
  Cache-Control: no-cache
  
  ------------Ij5GI3GI3ei4GI3ei4KM7GI3KM7KM7
  Content-Disposition: form-data; name="Filename"
  
  MyFile.jpg
  ------------Ij5GI3GI3ei4GI3ei4KM7GI3KM7KM7
  Content-Disposition: form-data; name="api_sig"
  
  XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
  ------------Ij5GI3GI3ei4GI3ei4KM7GI3KM7KM7
  Content-Disposition: form-data; name="api_key"
  
  XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
  ------------Ij5GI3GI3ei4GI3ei4KM7GI3KM7KM7
  Content-Disposition: form-data; name="auth_token"
  
  XXXXXXXXXXXXXXXXXXXXXX
  ------------Ij5GI3GI3ei4GI3ei4KM7GI3KM7KM7
  Content-Disposition: form-data; name="Filedata"; filename="MyFile.jpg"
  Content-Type: application/octet-stream
  
  FileDataHere
  ------------Ij5GI3GI3ei4GI3ei4KM7GI3KM7KM7
  Content-Disposition: form-data; name="Upload"
  
  Submit Query
  ------------Ij5GI3GI3ei4GI3ei4KM7GI3KM7KM7--
  
The following example displays the data format and status information for a file loaded at runtime.

Note: To run this example, change the uploadURL.url property to point to an actual URL, rather than the fictional one in the example. The URL should point to a file named yourUploadHandlerScript.cfm in the root web directory of the URL specified. Based on your configuration, you might also need to compile the SWF file with Local Playback Security set to Access Network Only or to update Flash Player security settings to allow this file network access.

package { import flash.display.Sprite; import flash.events.*; import flash.net.FileFilter; import flash.net.FileReference; import flash.net.URLRequest; public class FileReferenceExample extends Sprite { private var uploadURL:URLRequest; private var file:FileReference; public function FileReferenceExample() { uploadURL = new URLRequest(); uploadURL.url = "http://www.[yourDomain].com/yourUploadHandlerScript.cfm"; file = new FileReference(); configureListeners(file); file.browse(getTypes()); } private function configureListeners(dispatcher:IEventDispatcher):void { dispatcher.addEventListener(Event.CANCEL, cancelHandler); dispatcher.addEventListener(Event.COMPLETE, completeHandler); dispatcher.addEventListener(HTTPStatusEvent.HTTP_STATUS, httpStatusHandler); dispatcher.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler); dispatcher.addEventListener(Event.OPEN, openHandler); dispatcher.addEventListener(ProgressEvent.PROGRESS, progressHandler); dispatcher.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler); dispatcher.addEventListener(Event.SELECT, selectHandler); dispatcher.addEventListener(DataEvent.UPLOAD_COMPLETE_DATA,uploadCompleteDataHandler); } private function getTypes():Array { var allTypes:Array = new Array(getImageTypeFilter(), getTextTypeFilter()); return allTypes; } private function getImageTypeFilter():FileFilter { return new FileFilter("Images (*.jpg, *.jpeg, *.gif, *.png)", "*.jpg;*.jpeg;*.gif;*.png"); } private function getTextTypeFilter():FileFilter { return new FileFilter("Text Files (*.txt, *.rtf)", "*.txt;*.rtf"); } private function cancelHandler(event:Event):void { trace("cancelHandler: " + event); } private function completeHandler(event:Event):void { trace("completeHandler: " + event); } private function uploadCompleteDataHandler(event:DataEvent):void { trace("uploadCompleteData: " + event); } private function httpStatusHandler(event:HTTPStatusEvent):void { trace("httpStatusHandler: " + event); } private function ioErrorHandler(event:IOErrorEvent):void { trace("ioErrorHandler: " + event); } private function openHandler(event:Event):void { trace("openHandler: " + event); } private function progressHandler(event:ProgressEvent):void { var file:FileReference = FileReference(event.target); trace("progressHandler name=" + file.name + " bytesLoaded=" + event.bytesLoaded + " bytesTotal=" + event.bytesTotal); } private function securityErrorHandler(event:SecurityErrorEvent):void { trace("securityErrorHandler: " + event); } private function selectHandler(event:Event):void { var file:FileReference = FileReference(event.target); trace("selectHandler: name=" + file.name + " URL=" + uploadURL.url); file.upload(uploadURL); } } }
flash.net.FileReferenceListflash.filesystem.FileuploadCompleteData Dispatched after data is received from the server after a successful upload.flash.events.DataEvent.UPLOAD_COMPLETE_DATAflash.events.DataEvent Dispatched after data is received from the server after a successful upload. This event is not dispatched if data is not returned from the server. httpResponseStatus Dispatched if a call to the upload() or uploadUnencoded() method attempts to access data over HTTP and Adobe AIR is able to detect and return the status code for the request.flash.events.HTTPStatusEvent.HTTP_RESPONSE_STATUSflash.events.HTTPStatusEvent Dispatched if a call to the upload() or uploadUnencoded() method attempts to access data over HTTP and Adobe AIR is able to detect and return the status code for the request. upload()uploadUnencoded()httpStatus Dispatched when an upload fails and an HTTP status code is available to describe the failure.flash.events.HTTPStatusEvent.HTTP_STATUSflash.events.HTTPStatusEvent Dispatched when an upload fails and an HTTP status code is available to describe the failure. The httpStatus event is dispatched, followed by an ioError event.

The httpStatus event is dispatched only for upload failures. For content running in Flash Player this event is not applicable for download failures. If a download fails because of an HTTP error, the error is reported as an I/O error.

FileReference.upload()
select Dispatched when the user selects a file for upload or download from the file-browsing dialog box.flash.events.Event.SELECTflash.events.Event Dispatched when the user selects a file for upload or download from the file-browsing dialog box. (This dialog box opens when you call the FileReference.browse(), FileReferenceList.browse(), or FileReference.download() method.) When the user selects a file and confirms the operation (for example, by clicking OK), the properties of the FileReference object are populated.

For content running in Flash Player or outside of the application security sandbox in the Adobe AIR runtime, the select event acts slightly differently depending on what method invokes it. When the select event is dispatched after a browse() call, Flash Player or the AIR application can read all the FileReference object's properties, because the file selected by the user is on the local file system. When the select event occurs after a download() call, Flash Player or the AIR application can read only the name property, because the file hasn't yet been downloaded to the local file system at the moment the select event is dispatched. When the file is downloaded and the complete event dispatched, Flash Player or the AIR application can read all other properties of the FileReference object.

The following example shows usage of the select event object. To run this example, change the uploadURL.url property to point to an actual domain and file, rather than the fictional http://www.[yourDomain].com/SomeFile.pdf. You might also need to compile the SWF file with Local playback security set to Access network only or to update Flash Player security settings to allow this file network access. In order for this example to run from your desktop, your server also needs to have a crossdomain.xml file posted. If the ioErrorHandler() function is triggered, you probably need to update the provided uploadURL with a valid url that is configured to receive uploads. package { import flash.display.Sprite; import flash.events.*; import flash.net.FileReference; import flash.net.URLRequest; public class FileReference_event_select extends Sprite { private var uploadURL:URLRequest; private var file:FileReference; public function FileReference_event_select() { uploadURL = new URLRequest(); uploadURL.url = "http://www.[yourDomain].com/yourUploadHandlerScript.cfm"; file = new FileReference(); file.addEventListener(Event.SELECT, selectHandler); file.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler); file.addEventListener(ProgressEvent.PROGRESS, progressHandler); file.addEventListener(Event.COMPLETE, completeHandler); file.browse(); } private function selectHandler(event:Event):void { var file:FileReference = FileReference(event.target); trace("selectHandler: name=" + file.name + " URL=" + uploadURL.url); file.upload(uploadURL); } private function ioErrorHandler(event:IOErrorEvent):void { trace("ioErrorHandler: " + event); } private function progressHandler(event:ProgressEvent):void { var file:FileReference = FileReference(event.target); trace("progressHandler: name=" + file.name + " bytesLoaded=" + event.bytesLoaded + " bytesTotal=" + event.bytesTotal); } private function completeHandler(event:Event):void { trace("completeHandler: " + event); } } }
securityError Dispatched when a call to the FileReference.upload() or FileReference.download() method tries to upload a file to a server or get a file from a server that is outside the caller's security sandbox.flash.events.SecurityErrorEvent.SECURITY_ERRORflash.events.SecurityErrorEvent Dispatched when a call to the FileReference.upload() or FileReference.download() method tries to upload a file to a server or get a file from a server that is outside the caller's security sandbox. The value of the text property that describes the specific error that occurred is normally "securitySandboxError". The calling SWF file may have tried to access a SWF file outside its domain and does not have permission to do so. You can try to remedy this error by using a URL policy file.

In Adobe AIR, these security restrictions do not apply to content in the application security sandbox.

In Adobe AIR, these security restrictions do not apply to content in the application security sandbox.

FileReference.download()FileReference.upload()
progress Dispatched periodically during the file upload or download operation.flash.events.ProgressEvent.PROGRESSflash.events.ProgressEvent Dispatched periodically during the file upload or download operation. The progress event is dispatched while Flash Player transmits bytes to a server, and it is periodically dispatched during the transmission, even if the transmission is ultimately not successful. To determine if and when the file transmission is actually successful and complete, listen for the complete event.

In some cases, progress events are not received. For example, when the file being transmitted is very small or the upload or download happens very quickly a progress event might not be dispatched.

File upload progress cannot be determined on Macintosh platforms earlier than OS X 10.3. The progress event is called during the upload operation, but the value of the bytesLoaded property of the progress event is -1, indicating that the progress cannot be determined.

The following example shows usage of the progress event. To run this example, change the downloadURL.url property to point to an actual domain and file, rather than the fictional http://www.[yourDomain].com/SomeFile.pdf. You might also need to compile the SWF file with Local playback security set to Access network only or to update Flash Player security settings to allow this file network access. package { import flash.display.Sprite; import flash.events.*; import flash.net.FileReference; import flash.net.URLRequest; public class FileReference_event_progress extends Sprite { private var downloadURL:URLRequest; private var fileName:String = "SomeFile.pdf"; private var file:FileReference; public function FileReference_event_progress() { downloadURL = new URLRequest(); downloadURL.url = "http://www.[yourDomain].com/SomeFile.pdf"; file = new FileReference(); file.addEventListener(ProgressEvent.PROGRESS, progressHandler); file.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler); file.addEventListener(Event.COMPLETE, completeHandler); file.download(downloadURL, fileName); } private function progressHandler(event:ProgressEvent):void { var file:FileReference = FileReference(event.target); trace("progressHandler: name=" + file.name + " bytesLoaded=" + event.bytesLoaded + " bytesTotal=" + event.bytesTotal); } private function ioErrorHandler(event:IOErrorEvent):void { trace("ioErrorHandler: " + event); } private function completeHandler(event:Event):void { trace("completeHandler: " + event); } } }
FileReference.completeflash.events.ProgressEventFileReference.download()FileReference.upload()
open Dispatched when an upload or download operation starts.flash.events.Event.OPENflash.events.Event Dispatched when an upload or download operation starts. The following example shows usage of the download event object. To run this example, change the downloadURL.url property to point to an actual domain and file, rather than the fictional http://www.[yourDomain].com/SomeFile.pdf. You might also need to compile the SWF file with Local playback security set to Access network only or to update Flash Player security settings to allow this file network access. package { import flash.display.Sprite; import flash.events.*; import flash.net.FileReference; import flash.net.URLRequest; import flash.net.FileFilter; public class FileReference_download extends Sprite { private var downloadURL:URLRequest; private var fileName:String = "SomeFile.pdf"; private var file:FileReference; public function FileReference_download() { downloadURL = new URLRequest(); downloadURL.url = "http://www.[yourDomain].com/SomeFile.pdf"; file = new FileReference(); configureListeners(file); file.download(downloadURL, fileName); } private function configureListeners(dispatcher:IEventDispatcher):void { dispatcher.addEventListener(Event.CANCEL, cancelHandler); dispatcher.addEventListener(Event.COMPLETE, completeHandler); dispatcher.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler); dispatcher.addEventListener(Event.OPEN, openHandler); dispatcher.addEventListener(ProgressEvent.PROGRESS, progressHandler); dispatcher.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler); dispatcher.addEventListener(Event.SELECT, selectHandler); } private function cancelHandler(event:Event):void { trace("cancelHandler: " + event); } private function completeHandler(event:Event):void { trace("completeHandler: " + event); } private function ioErrorHandler(event:IOErrorEvent):void { trace("ioErrorHandler: " + event); } private function openHandler(event:Event):void { trace("openHandler: " + event); } private function progressHandler(event:ProgressEvent):void { var file:FileReference = FileReference(event.target); trace("progressHandler name=" + file.name + " bytesLoaded=" + event.bytesLoaded + " bytesTotal=" + event.bytesTotal); } private function securityErrorHandler(event:SecurityErrorEvent):void { trace("securityErrorHandler: " + event); } private function selectHandler(event:Event):void { var file:FileReference = FileReference(event.target); trace("selectHandler: name=" + file.name + " URL=" + downloadURL.url); } } } FileReference.download()FileReference.upload()ioError Dispatched when the upload or download fails.flash.events.IOErrorEvent.IO_ERRORflash.events.IOErrorEvent Dispatched when the upload or download fails. A file transfer can fail for one of the following reasons:
  • An input/output error occurs while the player is reading, writing, or transmitting the file.
  • The SWF file tries to upload a file to a server that requires authentication (such as a user name and password). During upload, Flash Player or Adobe AIR does not provide a means for users to enter passwords. If a SWF file tries to upload a file to a server that requires authentication, the upload fails.
  • The SWF file tries to download a file from a server that requires authentication, within the stand-alone or external player. During download, the stand-alone and external players do not provide a means for users to enter passwords. If a SWF file in these players tries to download a file from a server that requires authentication, the download fails. File download can succeed only in the ActiveX control, browser plug-in players, and the Adobe AIR runtime.
  • The value passed to the url parameter in the upload() method contains an invalid protocol. Valid protocols are HTTP and HTTPS.

Important: Only applications running in a browser — that is, using the browser plug-in or ActiveX control — and content running in Adobe AIR can provide a dialog box to prompt the user to enter a user name and password for authentication, and then only for downloads. For uploads using the plug-in or ActiveX control version of Flash Player, or for upload or download using either the stand-alone or the external player, the file transfer fails.

FileReference.download()FileReference.upload()
complete Dispatched when download is complete or when upload generates an HTTP status code of 200.flash.events.Event.COMPLETEflash.events.Event Dispatched when download is complete or when upload generates an HTTP status code of 200. For file download, this event is dispatched when Flash Player or Adobe AIR finishes downloading the entire file to disk. For file upload, this event is dispatched after the Flash Player or Adobe AIR receives an HTTP status code of 200 from the server receiving the transmission. The following example shows usage of the complete event object. To run this example, change the downloadURL.url property to point to an actual domain and file, rather than the fictional http://www.[yourDomain].com/SomeFile.pdf. You might also need to compile the SWF file with Local playback security set to Access network only or to update Flash Player security settings to allow this file network access. package { import flash.display.Sprite; import flash.events.*; import flash.net.FileReference; import flash.net.URLRequest; public class FileReference_event_complete extends Sprite { private var downloadURL:URLRequest; private var fileName:String = "SomeFile.pdf"; private var file:FileReference; public function FileReference_event_complete() { downloadURL = new URLRequest(); downloadURL.url = "http://www.[yourDomain].com/SomeFile.pdf"; file = new FileReference(); configureListeners(file); file.download(downloadURL, fileName); } private function configureListeners(dispatcher:IEventDispatcher):void { dispatcher.addEventListener(Event.CANCEL, cancelHandler); dispatcher.addEventListener(Event.COMPLETE, completeHandler); dispatcher.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler); dispatcher.addEventListener(Event.OPEN, openHandler); dispatcher.addEventListener(ProgressEvent.PROGRESS, progressHandler); dispatcher.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler); dispatcher.addEventListener(Event.SELECT, selectHandler); } private function cancelHandler(event:Event):void { trace("cancelHandler: " + event); } private function completeHandler(event:Event):void { trace("completeHandler: " + event); } private function ioErrorHandler(event:IOErrorEvent):void { trace("ioErrorHandler: " + event); } private function openHandler(event:Event):void { trace("openHandler: " + event); } private function progressHandler(event:ProgressEvent):void { var file:FileReference = FileReference(event.target); trace("progressHandler name=" + file.name + " bytesLoaded=" + event.bytesLoaded + " bytesTotal=" + event.bytesTotal); } private function securityErrorHandler(event:SecurityErrorEvent):void { trace("securityErrorHandler: " + event); } private function selectHandler(event:Event):void { var file:FileReference = FileReference(event.target); trace("selectHandler: name=" + file.name + " URL=" + downloadURL.url); } } } FileReference.download()FileReference.upload()cancel Dispatched when a file upload or download is canceled through the file-browsing dialog box by the user.flash.events.Event.CANCELflash.events.Event Dispatched when a file upload or download is canceled through the file-browsing dialog box by the user. Flash Player does not dispatch this event if the user cancels an upload or download through other means (closing the browser or stopping the current application). The following example shows usage of the cancel event object. To run this example, change the downloadURL.url property to point to an actual domain and file, rather than the fictional http://www.[yourDomain].com/SomeFile.pdf. You might also need to compile the SWF file with Local playback security set to Access network only or to update Flash Player security settings to allow this file network access. package { import flash.display.Sprite; import flash.events.*; import flash.net.FileReference; import flash.net.URLRequest; public class FileReference_event_cancel extends Sprite { private var downloadURL:URLRequest; private var fileName:String = "SomeFile.pdf"; private var file:FileReference; public function FileReference_event_cancel() { downloadURL = new URLRequest(); downloadURL.url = "http://www.[yourDomain].com/SomeFile.pdf"; file = new FileReference(); file.addEventListener(Event.CANCEL, cancelHandler); file.download(downloadURL, fileName); } private function cancelHandler(event:Event):void { trace("cancelHandler: " + event); } } } FileReference Creates a new FileReference object. Creates a new FileReference object. When populated, a FileReference object represents a file on the user's local disk. FileReference.browse()browse Displays a file-browsing dialog box that lets the user select a file to upload.Thrown in the following situations: 1) Another FileReference or FileReferenceList browse session is in progress; only one file browsing session may be performed at a time. 2) A setting in the user's mms.cfg file prohibits this operation. IllegalOperationErrorflash.errors:IllegalOperationErrorIf the typeFilter array contains FileFilter objects that are incorrectly formatted, an exception is thrown. For information on the correct format for FileFilter objects, see the FileFilter class. ArgumentErrorArgumentErrorIf the method is not called in response to a user action, such as a mouse event or keypress event. ErrorErrorReturns true if the parameters are valid and the file-browsing dialog box opens. BooleantypeFilterArraynullAn array of FileFilter instances used to filter the files that are displayed in the dialog box. If you omit this parameter, all files are displayed. For more information, see the FileFilter class. Displays a file-browsing dialog box that lets the user select a file to upload. The dialog box is native to the user's operating system. The user can select a file on the local computer or from other systems, for example, through a UNC path on Windows.

Note: The File class, available in Adobe AIR, includes methods for accessing more specific system file selection dialog boxes. These methods are File.browseForDirectory(), File.browseForOpen(), File.browseForOpenMultiple(), and File.browseForSave().

When you call this method and the user successfully selects a file, the properties of this FileReference object are populated with the properties of that file. Each subsequent time that the FileReference.browse() method is called, the FileReference object's properties are reset to the file that the user selects in the dialog box. Only one browse() or download() session can be performed at a time (because only one dialog box can be invoked at a time).

Using the typeFilter parameter, you can determine which files the dialog box displays.

In Flash Player 10 and Flash Player 9 Update 5, you can only call this method successfully in response to a user event (for example, in an event handler for a mouse click or keypress event). Otherwise, calling this method results in Flash Player throwing an Error exception.

Note that because of new functionality added to the Flash Player, when publishing to Flash Player 10, you can have only one of the following operations active at one time: FileReference.browse(), FileReference.upload(), FileReference.download(), FileReference.load(), FileReference.save(). Otherwise, Flash Player throws a runtime error (code 2174). Use FileReference.cancel() to stop an operation in progress. This restriction applies only to Flash Player 10. Previous versions of Flash Player are unaffected by this restriction on simultaneous multiple operations.

In Adobe AIR, the file-browsing dialog is not always displayed in front of windows that are "owned" by another window (windows that have a non-null owner property). To avoid window ordering issues, hide owned windows before calling this method.

select eventcancel eventFileReference.download()FileReferenceList.browse()File.browseForDirectory()File.browseForOpen()File.browseForOpenMultiple()File.browseForSave()selectflash.events:EventDispatched when the user successfully selects an item from the Browse file chooser. Dispatched when the user successfully selects an item from the Browse file chooser.cancelflash.events:EventDispatched when the user cancels the file upload Browse window. Dispatched when the user cancels the file upload Browse window.
cancel Cancels any ongoing upload or download operation on this FileReference object.Cancels any ongoing upload or download. Cancels any ongoing upload or download operation on this FileReference object. Calling this method does not dispatch the cancel event; that event is dispatched only when the user cancels the operation by dismissing the file upload or download dialog box. download Opens a dialog box that lets the user download a file from a remote server.Thrown in the following situations: 1) Another browse session is in progress; only one file browsing session can be performed at a time. 2) The value passed to request does not contain a valid path or protocol. 3) The filename to download contains prohibited characters. 4) A setting in the user's mms.cfg file prohibits this operation. IllegalOperationErrorflash.errors:IllegalOperationErrorLocal untrusted content may not communicate with the Internet. To avoid this situation, reclassify this SWF file as local-with-networking or trusted. This exception is thrown with a message indicating the filename and the URL that may not be accessed because of local file security restrictions. SecurityErrorSecurityErrorYou cannot connect to commonly reserved ports. For a complete list of blocked ports, see "Restricting Networking APIs" in the ActionScript 3.0 Developer's Guide. SecurityErrorSecurityErrorIf url.data is of type ByteArray, an exception is thrown. For use with the FileReference.upload() and FileReference.download() methods, url.data can only be of type URLVariables or String. ArgumentErrorArgumentErrorThis error can occur for the following reasons: 1) Flash Player cannot convert the URLRequest.data parameter from UTF8 to MBCS. This error is applicable if the URLRequest object passed to the FileReference.download() method is set to perform a GET operation and if System.useCodePage is set to true. 2) Flash Player cannot allocate memory for the POST data. This error is applicable if the URLRequest object passed to the FileReference.download() method is set to perform a POST operation. MemoryErrorflash.errors:MemoryErrorIf the method is not called in response to a user action, such as a mouse event or keypress event. ErrorErrorrequestflash.net:URLRequestThe URLRequest object. The url property of the URLRequest object should contain the URL of the file to download to the local computer. If this parameter is null, an exception is thrown. The requestHeaders property of the URLRequest object is ignored; custom HTTP request headers are not supported in uploads or downloads. To send POST or GET parameters to the server, set the value of URLRequest.data to your parameters, and set URLRequest.method to either URLRequestMethod.POST or URLRequestMethod.GET.

On some browsers, URL strings are limited in length. Lengths greater than 256 characters may fail on some browsers or servers.

defaultFileNameStringnullThe default filename displayed in the dialog box for the file to be downloaded. This string must not contain the following characters: / \ : ~~ ? " < > | %

If you omit this parameter, the filename of the remote URL is parsed and used as the default.

Opens a dialog box that lets the user download a file from a remote server. Although Flash Player has no restriction on the size of files you can upload or download, the player officially supports uploads or downloads of up to 100 MB.

The download() method first opens an operating-system dialog box that asks the user to enter a filename and select a location on the local computer to save the file. When the user selects a location and confirms the download operation (for example, by clicking Save), the download from the remote server begins. Listeners receive events to indicate the progress, success, or failure of the download. To ascertain the status of the dialog box and the download operation after calling download(), your code must listen for events such as cancel, open, progress, and complete.

The FileReference.upload() and FileReference.download() functions are nonblocking. These functions return after they are called, before the file transmission is complete. In addition, if the FileReference object goes out of scope, any upload or download that is not yet completed on that object is canceled upon leaving the scope. Be sure that your FileReference object remains in scope for as long as the upload or download is expected to continue.

When the file is downloaded successfully, the properties of the FileReference object are populated with the properties of the local file. The complete event is dispatched if the download is successful.

Only one browse() or download() session can be performed at a time (because only one dialog box can be invoked at a time).

This method supports downloading of any file type, with either HTTP or HTTPS.

You cannot connect to commonly reserved ports. For a complete list of blocked ports, see "Restricting Networking APIs" in the ActionScript 3.0 Developer's Guide.

Note: If your server requires user authentication, only SWF files running in a browser — that is, using the browser plug-in or ActiveX control — can provide a dialog box to prompt the user for a user name and password for authentication, and only for downloads. For uploads using the plug-in or ActiveX control, or for uploads and downloads using the stand-alone or external player, the file transfer fails.

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

  • Loading operations are not allowed if the calling SWF file is in an untrusted local sandbox.
  • The default behavior is to deny access between sandboxes. A website can enable access to a resource by adding a URL policy file.
  • You can prevent a SWF file from using this method by setting the allowNetworking parameter of the the object and embed tags in the HTML page that contains the SWF content.
  • In Flash Player 10 and Flash Player 9 Update 5, you can only call this method successfully in response to a user event (for example, in an event handler for a mouse click or keypress event). Otherwise, calling this method results in Flash Player throwing an Error exception.

However, in Adobe AIR, content in the application security sandbox (content installed with the AIR application) is not restricted by these security limitations.

For more information related to security, see the Flash Player Developer Center Topic: Security.

When you download a file using this method, it is flagged as downloaded on operating systems that flag downloaded files:

  • Windows XP service pack 2 and later, and on Windows Vista
  • Mac OS 10.5 and later

Some operating systems, such as Linux, do not flag downloaded files.

Note that because of new functionality added to the Flash Player, when publishing to Flash Player 10, you can have only one of the following operations active at one time: FileReference.browse(), FileReference.upload(), FileReference.download(), FileReference.load(), FileReference.save(). Otherwise, Flash Player throws a runtime error (code 2174). Use FileReference.cancel() to stop an operation in progress. This restriction applies only to Flash Player 10. Previous versions of Flash Player are unaffected by this restriction on simultaneous multiple operations.

In Adobe AIR, the download dialog is not always displayed in front of windows that are "owned" by another window (windows that have a non-null owner property). To avoid window ordering issues, hide owned windows before calling this method.

The following example shows usage of the download event object. To run this example, change the downloadURL.url property to point to an actual domain and file, rather than the fictional http://www.[yourDomain].com/SomeFile.pdf. You might also need to compile the SWF file with Local playback security set to Access network only or to update Flash Player security settings to allow this file network access. package { import flash.display.Sprite; import flash.events.*; import flash.net.FileReference; import flash.net.URLRequest; import flash.net.FileFilter; public class FileReference_download extends Sprite { private var downloadURL:URLRequest; private var fileName:String = "SomeFile.pdf"; private var file:FileReference; public function FileReference_download() { downloadURL = new URLRequest(); downloadURL.url = "http://www.[yourDomain].com/SomeFile.pdf"; file = new FileReference(); configureListeners(file); file.download(downloadURL, fileName); } private function configureListeners(dispatcher:IEventDispatcher):void { dispatcher.addEventListener(Event.CANCEL, cancelHandler); dispatcher.addEventListener(Event.COMPLETE, completeHandler); dispatcher.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler); dispatcher.addEventListener(Event.OPEN, openHandler); dispatcher.addEventListener(ProgressEvent.PROGRESS, progressHandler); dispatcher.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler); dispatcher.addEventListener(Event.SELECT, selectHandler); } private function cancelHandler(event:Event):void { trace("cancelHandler: " + event); } private function completeHandler(event:Event):void { trace("completeHandler: " + event); } private function ioErrorHandler(event:IOErrorEvent):void { trace("ioErrorHandler: " + event); } private function openHandler(event:Event):void { trace("openHandler: " + event); } private function progressHandler(event:ProgressEvent):void { var file:FileReference = FileReference(event.target); trace("progressHandler name=" + file.name + " bytesLoaded=" + event.bytesLoaded + " bytesTotal=" + event.bytesTotal); } private function securityErrorHandler(event:SecurityErrorEvent):void { trace("securityErrorHandler: " + event); } private function selectHandler(event:Event):void { var file:FileReference = FileReference(event.target); trace("selectHandler: name=" + file.name + " URL=" + downloadURL.url); } } }
File.downloadedFileReference.browse()FileReferenceList.browse()FileReference.upload()FileReference.save()openflash.events:EventDispatched when a download operation starts. Dispatched when a download operation starts.progressflash.events:ProgressEventDispatched periodically during the file download operation. Dispatched periodically during the file download operation.completeflash.events:EventDispatched when the file download operation successfully completes. Dispatched when the file download operation successfully completes.cancelflash.events:EventDispatched when the user dismisses the dialog box. Dispatched when the user dismisses the dialog box.selectflash.events:EventDispatched when the user selects a file for download from the dialog box. Dispatched when the user selects a file for download from the dialog box.securityErrorflash.events:SecurityErrorEventDispatched when a download fails because of a security error. Dispatched when a download fails because of a security error.ioErrorflash.events:IOErrorEventDispatched for any of the following reasons:
  • An input/output error occurs while the file is being read or transmitted.
  • SWF content running in the stand-alone or external versions of Flash Player tries to download a file from a server that requires authentication. During download, the standalone and external players do not provide a means for users to enter passwords. If a SWF file in these players tries to download a file from a server that requires authentication, the download fails. File download can succeed only in the ActiveX control and browser plug-in players.
Dispatched for any of the following reasons: An input/output error occurs while the file is being read or transmitted. SWF content running in the stand-alone or external versions of Flash Player tries to download a file from a server that requires authentication.
load Starts the load of a local file selected by a user.Thrown in the following situations: 1) Another FileReference or FileReferenceList browse session is in progress; only one file browsing session may be performed at a time. 2) A setting in the user's mms.cfg file prohibits this operation. IllegalOperationErrorflash.errors:IllegalOperationErrorThis error can occur if the application cannot allocate memory for the file. The file may be too large or available memory may be too low. MemoryErrorflash.errors:MemoryErrorStarts the load of a local file. Starts the load of a local file selected by a user. Although Flash Player has no restriction on the size of files you can upload, download, load or save, it officially supports sizes of up to 100 MB. For content running in Flash Player, you must call the FileReference.browse() or FileReferenceList.browse() method before you call the load() method. However, content running in AIR in the application sandbox can call the load() method of a File object without first calling the browse() method. (The AIR File class extends the FileReference class.)

Listeners receive events to indicate the progress, success, or failure of the load. Although you can use the FileReferenceList object to let users select multiple files to load, you must load the files one by one. To load the files one by one, iterate through the FileReferenceList.fileList array of FileReference objects.

Adobe AIR also includes the FileStream class which provides more options for reading files.

The FileReference.upload(), FileReference.download(), FileReference.load() and FileReference.save() functions are nonblocking. These functions return after they are called, before the file transmission is complete. In addition, if the FileReference object goes out of scope, any transaction that is not yet completed on that object is canceled upon leaving the scope. Be sure that your FileReference object remains in scope for as long as the upload, download, load or save is expected to continue.

If the file finishes loading successfully, its contents are stored as a byte array in the data property of the FileReference object.

The following security considerations apply:

  • Loading operations are not allowed if the calling SWF file is in an untrusted local sandbox.
  • The default behavior is to deny access between sandboxes. A website can enable access to a resource by adding a cross-domain policy file.
  • You can prevent a file from using this method by setting the allowNetworking parameter of the the object and embed tags in the HTML page that contains the SWF content.

However, these considerations do not apply to AIR content in the application sandbox.

Note that when publishing to Flash Player 10 or AIR 1.5, you can have only one of the following operations active at one time: FileReference.browse(), FileReference.upload(), FileReference.download(), FileReference.load(), FileReference.save(). Otherwise, the application throws a runtime error (code 2174). Use FileReference.cancel() to stop an operation in progress. This restriction applies only to Flash Player 10 and AIR 1.5. Previous versions of Flash Player or AIR are unaffected by this restriction on simultaneous multiple operations.

In Adobe AIR, the file-browsing dialog is not always displayed in front of windows that are "owned" by another window (windows that have a non-null owner property). To avoid window ordering issues, hide owned windows before calling this method.

The following example uploads an image from your local file system to the root display object (in this case, the stage). Example provided by Andre Venancio. var buttonShape:Shape = new Shape(); buttonShape.graphics.beginFill(0x336699); buttonShape.graphics.drawCircle(50, 50, 25); var button = new SimpleButton(buttonShape, buttonShape, buttonShape, buttonShape); addChild(button); var fileRef:FileReference= new FileReference(); button.addEventListener(MouseEvent.CLICK, onButtonClick); function onButtonClick(e:MouseEvent):void { fileRef.browse([new FileFilter("Images", "*.jpg;*.gif;*.png")]); fileRef.addEventListener(Event.SELECT, onFileSelected); } function onFileSelected(e:Event):void { fileRef.addEventListener(Event.COMPLETE, onFileLoaded); fileRef.load(); } function onFileLoaded(e:Event):void { var loader:Loader = new Loader(); loader.loadBytes(e.target.data); addChild(loader); }
FileReference.browse()FileReferenceList.browse()FileReference.dataFileReferenceList.fileListFileReference.save()FileStreamopenflash.events:EventDispatched when an load operation starts. Dispatched when an load operation starts.progressflash.events:ProgressEventDispatched periodically during the file load operation. Dispatched periodically during the file load operation.completeflash.events:EventDispatched when the file load operation completes successfully. Dispatched when the file load operation completes successfully.ioErrorflash.events:IOErrorEventInvoked if the load fails because of an input/output error while the application is reading or writing the file. Invoked if the load fails because of an input/output error while the application is reading or writing the file.
save Opens a dialog box that lets the user save a file to the local filesystem.Thrown in the following situations: 1) Another browse session is in progress; only one file browsing session can be performed at a time. 2) The filename to download contains prohibited characters. 3) A setting in the user's mms.cfg file prohibits this operation. IllegalOperationErrorflash.errors:IllegalOperationErrorIf data is not of type ByteArray, and it does not have a toString() method, an exception is thrown. If data is not of type XML, and it does not have a toXMLString() method, an exception is thrown. ArgumentErrorArgumentErrorIf the method is not called in response to a user action, such as a mouse event or keypress event. ErrorErrorThis error can occur if Flash Player cannot allocate memory for the file. The file may be too large or available memory may be too low. MemoryErrorflash.errors:MemoryErrordataThe data to be saved. The data can be in one of several formats, and will be treated appropriately:
  • If the value is null, the application throws an ArgumentError exception.
  • If the value is a String, it is saved as a UTF-8 text file.
  • If the value is XML, it is written to a text file in XML format, with all formatting preserved.
  • If the value is a ByteArray object, it is written to a data file verbatim.
  • If the value is none of the above, the save() method calls the toString() method of the object to convert the data to a string, and it then saves the data as a text file. If that fails, the application throws an ArgumentError exception.
defaultFileNameStringnullThe default filename displayed in the dialog box for the file to be saved. This string must not contain the following characters: / \ : ~~ ? " < > | %

If a File object calls this method, the filename will be that of the file the File object references. (The AIR File class extends the FileReference class.)

Opens a dialog box that lets the user save a file to the local filesystem. Although Flash Player has no restriction on the size of files you can upload, download, load or save, the player officially supports sizes of up to 100 MB.

The save() method first opens an operating-system dialog box that asks the user to enter a filename and select a location on the local computer to save the file. When the user selects a location and confirms the save operation (for example, by clicking Save), the save process begins. Listeners receive events to indicate the progress, success, or failure of the save operation. To ascertain the status of the dialog box and the save operation after calling save(), your code must listen for events such as cancel, open, progress, and complete.

Adobe AIR also includes the FileStream class which provides more options for saving files locally.

The FileReference.upload(), FileReference.download(), FileReference.load() and FileReference.save() functions are nonblocking. These functions return after they are called, before the file transmission is complete. In addition, if the FileReference object goes out of scope, any transaction that is not yet completed on that object is canceled upon leaving the scope. Be sure that your FileReference object remains in scope for as long as the upload, download, load or save is expected to continue.

When the file is saved successfully, the properties of the FileReference object are populated with the properties of the local file. The complete event is dispatched if the save is successful.

Only one browse() or save() session can be performed at a time (because only one dialog box can be invoked at a time).

In Flash Player, you can only call this method successfully in response to a user event (for example, in an event handler for a mouse click or keypress event). Otherwise, calling this method results in Flash Player throwing an Error exception. This limitation does not apply to AIR content in the application sandbox.

In Adobe AIR, the save dialog is not always displayed in front of windows that are "owned" by another window (windows that have a non-null owner property). To avoid window ordering issues, hide owned windows before calling this method.

The following example saves the content typed into a text field to a file. The example creates an editable text field (MyTextField) and another text field that is not editable (MyButtonField)to serve as a "button" to respond to a mouse click. A user can edit the first text field and click the button to save the text field contents to a local file. The mouse click event handler clickhandler uses the FileReference.save() method (for a FileReference object named MyFileReference) to open a dialog on the user's current operating system so the user can save the contents to a local file with the name the user provides. var MyTextField:TextField = new TextField(); var MyButtonField:TextField = new TextField(); var MyFile:FileReference = new FileReference(); MyTextField.border = true; MyTextField.type = TextFieldType.INPUT; MyButtonField.background = true; MyButtonField.backgroundColor = 0x339933; MyButtonField.x = 150; MyButtonField.height = 20; MyButtonField.text = "Click here to save"; addChild(MyTextField); addChild(MyButtonField); MyButtonField.addEventListener(MouseEvent.CLICK, clickhandler); function clickhandler(e:MouseEvent): void { MyFile.save(MyTextField.text); }
FileReferenceList.browse()FileReference.load()FileReference.dataFileReference.upload()FileReference.download()FileStreamopenflash.events:EventDispatched when a download operation starts. Dispatched when a download operation starts.progressflash.events:ProgressEventDispatched periodically during the file download operation. Dispatched periodically during the file download operation.completeflash.events:EventDispatched when the file download operation successfully completes. Dispatched when the file download operation successfully completes.cancelflash.events:EventDispatched when the user dismisses the dialog box. Dispatched when the user dismisses the dialog box.selectflash.events:EventDispatched when the user selects a file for download from the dialog box. Dispatched when the user selects a file for download from the dialog box.ioErrorflash.events:IOErrorEventDispatched if an input/output error occurs while the file is being read or transmitted. Dispatched if an input/output error occurs while the file is being read or transmitted.
uploadUnencoded Initiate uploading a file to a URL without any encoding.Local untrusted SWF files may not communicate with the Internet. To avoid this situation, reclassify this SWF file as local-with-networking or trusted. This exception is thrown with a message indicating the name of the local file and the URL that may not be accessed. SecurityErrorSecurityErrorThrown in the following situations: 1) Another FileReference or FileReferenceList browse session is in progress; only one file browsing session may be performed at a time. 2) The URL parameter is not a valid path or protocol. File upload must use HTTP. IllegalOperationErrorflash.errors:IllegalOperationErrorrequestflash.net:URLRequestThe URLRequest object; the url property of the URLRequest object should contain the URL of the server script configured to handle upload through HTTP POST calls. On some browsers, URL strings are limited in length. Lengths greater than 256 characters may fail on some browsers or servers. If this parameter is null, an exception is thrown.

The URL can be HTTP or, for secure uploads, HTTPS. To use HTTPS, use an HTTPS url in the url parameter. If you do not specify a port number in the url parameter, port 80 is used for HTTP and port 443 us used for HTTPS, by default.

To send POST or GET parameters to the server, set the data property of the URLRequest object to your parameters, and set the method property to either URLRequestMethod.POST or URLRequestMethod.GET.

Starts the upload of a file to a remote server without encoding.
Initiate uploading a file to a URL without any encoding. Whereas the upload() method encodes the file in a form-data envelope, the uploadUnencoded() method passes the file contents as-is in the HTTP request body. Use the uploadUnencoded() method if the data you wish to send is already encoded in a format that the receiving server can understand.You typically use the uploadeUnencoded() method with the HTTP/WebDAV PUT method.
FileReference.browse()FileReferenceList.browse()FileReference.download()FileReferenceList.fileListupload()openflash.events:EventDispatched when an upload operation starts. Dispatched when an upload operation starts.progressflash.events:ProgressEventDispatched periodically during the file upload operation. Dispatched periodically during the file upload operation.completeflash.events:EventDispatched when the file upload operation completes successfully. Dispatched when the file upload operation completes successfully.uploadCompleteDataflash.events:DataEventDispatched when data has been received from the server after a successful file upload. Dispatched when data has been received from the server after a successful file upload.securityErrorflash.events:SecurityErrorEventDispatched when an upload fails because of a security violation. Dispatched when an upload fails because of a security violation.httpStatusflash.events:HTTPStatusEventDispatched when an upload fails because of an HTTP error. Dispatched when an upload fails because of an HTTP error.httpResponseStatusflash.events:HTTPStatusEventThe upload operation completes successfully and the server returns a response URL and response headers. The upload operation completes successfully and the server returns a response URL and response headers.ioErrorflash.events:IOErrorEventInvoked in any of the following situations:
  • The upload fails because of an input/output error while Adobe AIR is reading, writing, or transmitting the file.
  • The upload fails because an attempt to upload a file to a server that requires authentication (such as a user name and password). During upload, no mean is provided for users to enter passwords.
  • The upload fails because the url parameter contains an invalid protocol. FileReference.upload() must use HTTP or HTTPS.
Invoked in any of the following situations: The upload fails because of an input/output error while Adobe AIR is reading, writing, or transmitting the file. The upload fails because an attempt to upload a file to a server that requires authentication (such as a user name and password).
upload Starts the upload of the file to a remote server.Local untrusted SWF files may not communicate with the Internet. To avoid this situation, reclassify this SWF file as local-with-networking or trusted. This exception is thrown with a message indicating the name of the local file and the URL that may not be accessed. SecurityErrorSecurityErrorYou cannot connect to commonly reserved ports. For a complete list of blocked ports, see "Restricting Networking APIs" in the ActionScript 3.0 Developer's Guide. SecurityErrorSecurityErrorThrown in the following situations: 1) Another FileReference or FileReferenceList browse session is in progress; only one file browsing session may be performed at a time. 2) The URL parameter is not a valid path or protocol. File upload must use HTTP, and file download must use FTP or HTTP. 3) The uploadDataFieldName parameter is set to null. 4) A setting in the user's mms.cfg file prohibits this operation. IllegalOperationErrorflash.errors:IllegalOperationErrorThrown in the following situations: 1) The uploadDataFieldName parameter is an empty string. 2) url.data is of type ByteArray. For use with the FileReference.upload() and FileReference.download() methods, url.data may only be of type URLVariables or String. 3) In the AIR runtime (in the application security sandbox), the method of the URLRequest is not GET or POST (use uploadEncoded() instead). ArgumentErrorArgumentErrorThis error can occur for the following reasons: 1) Flash Player cannot convert the URLRequest.data parameter from UTF8 to MBCS. This error is applicable if the URLRequest object passed to FileReference.upload() is set to perform a GET operation and if System.useCodePage is set to true. 2) Flash Player cannot allocate memory for the POST data. This error is applicable if the URLRequest object passed to FileReference.upload() is set to perform a POST operation. MemoryErrorflash.errors:MemoryErrorrequestflash.net:URLRequestThe URLRequest object; the url property of the URLRequest object should contain the URL of the server script configured to handle upload through HTTP POST calls. On some browsers, URL strings are limited in length. Lengths greater than 256 characters may fail on some browsers or servers. If this parameter is null, an exception is thrown. The requestHeaders property of the URLRequest object is ignored; custom HTTP request headers are not supported in uploads or downloads.

The URL can be HTTP or, for secure uploads, HTTPS. To use HTTPS, use an HTTPS url in the url parameter. If you do not specify a port number in the url parameter, port 80 is used for HTTP and port 443 us used for HTTPS, by default.

To send POST or GET parameters to the server, set the data property of the URLRequest object to your parameters, and set the method property to either URLRequestMethod.POST or URLRequestMethod.GET.

uploadDataFieldNameStringFiledataThe field name that precedes the file data in the upload POST operation. The uploadDataFieldName value must be non-null and a non-empty String. By default, the value of uploadDataFieldName is "Filedata", as shown in the following sample POST request:
    Content-Type: multipart/form-data; boundary=AaB03x
    --AaB03x 
    Content-Disposition: form-data; name="Filedata"; filename="example.jpg" 
    Content-Type: application/octet-stream
    ... contents of example.jpg ... 
    --AaB03x-- 
    
testUploadBooleanfalseA setting to request a test file upload. If testUpload is true, for files larger than 10 KB, Flash Player attempts a test file upload POST with a Content-Length of 0. The test upload checks whether the actual file upload will be successful and that server authentication, if required, will succeed. A test upload is only available for Windows players. Starts the upload of a file to a remote server.
Starts the upload of the file to a remote server. Although Flash Player has no restriction on the size of files you can upload or download, the player officially supports uploads or downloads of up to 100 MB. You must call the FileReference.browse() or FileReferenceList.browse() method before you call this method.

For the Adobe AIR File class, which extends the FileReference class, you can use the upload() method to upload any file. For the FileReference class (used in Flash Player), the user must first select a file.

Listeners receive events to indicate the progress, success, or failure of the upload. Although you can use the FileReferenceList object to let users select multiple files for upload, you must upload the files one by one; to do so, iterate through the FileReferenceList.fileList array of FileReference objects.

The FileReference.upload() and FileReference.download() functions are nonblocking. These functions return after they are called, before the file transmission is complete. In addition, if the FileReference object goes out of scope, any upload or download that is not yet completed on that object is canceled upon leaving the scope. Be sure that your FileReference object remains in scope for as long as the upload or download is expected to continue.

The file is uploaded to the URL passed in the url parameter. The URL must be a server script configured to accept uploads. Flash Player uploads files by using the HTTP POST method. The server script that handles the upload should expect a POST request with the following elements:

  • Content-Type of multipart/form-data
  • Content-Disposition with a name attribute set to "Filedata" by default and a filename attribute set to the name of the original file
  • The binary contents of the file

You cannot connect to commonly reserved ports. For a complete list of blocked ports, see "Restricting Networking APIs" in the ActionScript 3.0 Developer's Guide.

For a sample POST request, see the description of the uploadDataFieldName parameter. You can send POST or GET parameters to the server with the upload() method; see the description of the request parameter.

If the testUpload parameter is true, and the file to be uploaded is bigger than approximately 10 KB, Flash Player on Windows first sends a test upload POST operation with zero content before uploading the actual file, to verify that the transmission is likely to succeed. Flash Player then sends a second POST operation that contains the actual file content. For files smaller than 10 KB, Flash Player performs a single upload POST with the actual file content to be uploaded. Flash Player on Macintosh does not perform test upload POST operations.

Note: If your server requires user authentication, only SWF files running in a browser — that is, using the browser plug-in or ActiveX control — can provide a dialog box to prompt the user for a username and password for authentication, and only for downloads. For uploads using the plug-in or ActiveX control, or for uploads and downloads using the stand-alone or external player, the file transfer fails.

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

  • Loading operations are not allowed if the calling SWF file is in an untrusted local sandbox.
  • The default behavior is to deny access between sandboxes. A website can enable access to a resource by adding a URL policy file.
  • You can prevent a SWF file from using this method by setting the allowNetworking parameter of the the object and embed tags in the HTML page that contains the SWF content.

However, in Adobe AIR, content in the application security sandbox (content installed with the AIR application) are not restricted by these security limitations.

For more information related to security, see the Flash Player Developer Center Topic: Security.

Note that because of new functionality added to the Flash Player, when publishing to Flash Player 10, you can have only one of the following operations active at one time: FileReference.browse(), FileReference.upload(), FileReference.download(), FileReference.load(), FileReference.save(). Otherwise, Flash Player throws a runtime error (code 2174). Use FileReference.cancel() to stop an operation in progress. This restriction applies only to Flash Player 10. Previous versions of Flash Player are unaffected by this restriction on simultaneous multiple operations.

FileReference.browse()FileReferenceList.browse()FileReference.download()FileReferenceList.fileListFileReference.load()openflash.events:EventDispatched when an upload operation starts. Dispatched when an upload operation starts.progressflash.events:ProgressEventDispatched periodically during the file upload operation. Dispatched periodically during the file upload operation.completeflash.events:EventDispatched when the file upload operation completes successfully. Dispatched when the file upload operation completes successfully.uploadCompleteDataflash.events:DataEventDispatched when data has been received from the server after a successful file upload. Dispatched when data has been received from the server after a successful file upload.securityErrorflash.events:SecurityErrorEventDispatched when an upload fails because of a security violation. Dispatched when an upload fails because of a security violation.httpStatusflash.events:HTTPStatusEventDispatched when an upload fails because of an HTTP error. Dispatched when an upload fails because of an HTTP error.httpResponseStatusflash.events:HTTPStatusEventThe upload operation completes successfully and the server returns a response URL and response headers. The upload operation completes successfully and the server returns a response URL and response headers.ioErrorflash.events:IOErrorEventInvoked in any of the following situations:
  • The upload fails because of an input/output error while Flash Player or Adobe AIR is reading, writing, or transmitting the file.
  • The upload fails because an attempt to upload a file to a server that requires authentication (such as a user name and password). During upload, no mean is provided for users to enter passwords.
  • The upload fails because the url parameter contains an invalid protocol. FileReference.upload() must use HTTP or HTTPS.
Invoked in any of the following situations: The upload fails because of an input/output error while Flash Player or Adobe AIR is reading, writing, or transmitting the file. The upload fails because an attempt to upload a file to a server that requires authentication (such as a user name and password).
creationDate The creation date of the file on the local disk.DateIf the FileReference.browse(), FileReferenceList.browse(), or FileReference.download() method was not called successfully, an exception is thrown with a message indicating that functions were called in the incorrect sequence or an earlier call was unsuccessful. In this case, the value of the creationDate property is null. IllegalOperationErrorflash.errors:IllegalOperationErrorIf the file information cannot be accessed, an exception is thrown with a message indicating a file I/O error. IOErrorflash.errors:IOErrorGets the creation date of the file as a Date object. The creation date of the file on the local disk. If the object is was not populated, a call to get the value of this property returns null. FileReference.browse()creator The Macintosh creator type of the file, which is only used in Mac OS versions prior to Mac OS X.StringOn Macintosh, if the FileReference.browse(), FileReferenceList.browse(), or FileReference.download() method was not called successfully, an exception is thrown with a message indicating that functions were called in the incorrect sequence or an earlier call was unsuccessful. In this case, the value of the creator property is null. IllegalOperationErrorflash.errors:IllegalOperationErrorThe Macintosh creator type. The Macintosh creator type of the file, which is only used in Mac OS versions prior to Mac OS X. In Windows or Linux, this property is null. If the FileReference object was not populated, a call to get the value of this property returns null. FileReference.browse()FileReference.extensiondata The ByteArray object representing the data from the loaded file after a successful call to the load() method.flash.utils:ByteArrayIf the load() method was not called successfully, an exception is thrown with a message indicating that functions were called in the incorrect sequence or an earlier call was unsuccessful. In this case, the value of the data property is null. IllegalOperationErrorflash.errors:IllegalOperationErrorIf the file cannot be opened or read, or if a similar error is encountered in accessing the file, an exception is thrown with a message indicating a file I/O error. In this case, the value of the data property is null. IOErrorflash.errors:IOErrorThe loaded data of the file, as a ByteArray. The ByteArray object representing the data from the loaded file after a successful call to the load() method. FileReference.browse()FileReference.load()extension The filename extension.StringIf the reference is not initialized. IllegalOperationErrorflash.errors:IllegalOperationError The filename extension.

A file's extension is the part of the name following (and not including) the final dot ("."). If there is no dot in the filename, the extension is null.

Note: You should use the extension property to determine a file's type; do not use the creator or type properties. You should consider the creator and type properties to be considered deprecated. They apply to older versions of Mac OS.

modificationDate The date that the file on the local disk was last modified.DateIf the FileReference.browse(), FileReferenceList.browse(), or FileReference.download() method was not called successfully, an exception is thrown with a message indicating that functions were called in the incorrect sequence or an earlier call was unsuccessful. In this case, the value of the modificationDate property is null. IllegalOperationErrorflash.errors:IllegalOperationErrorIf the file information cannot be accessed, an exception is thrown with a message indicating a file I/O error. IOErrorflash.errors:IOErrorGets the modification date of the file as a Date object. The date that the file on the local disk was last modified. If the FileReference object was not populated, a call to get the value of this property returns null. FileReference.browse()name The name of the file on the local disk.StringIf the FileReference.browse(), FileReferenceList.browse(), or FileReference.download() method was not called successfully, an exception is thrown with a message indicating that functions were called in the incorrect sequence or an earlier call was unsuccessful. IllegalOperationErrorflash.errors:IllegalOperationErrorGets the name of the file as a String. The name of the file on the local disk. If the FileReference object was not populated (by a valid call to FileReference.download() or FileReference.browse()), Flash Player throws an error when you try to get the value of this property.

All the properties of a FileReference object are populated by calling the browse() method. Unlike other FileReference properties, if you call the download() method, the name property is populated when the select event is dispatched.

FileReference.browse()
size The size of the file on the local disk in bytes.NumberIf the FileReference.browse(), FileReferenceList.browse(), or FileReference.download() method was not called successfully, an exception is thrown with a message indicating that functions were called in the incorrect sequence or an earlier call was unsuccessful. IllegalOperationErrorflash.errors:IllegalOperationErrorIf the file cannot be opened or read, or if a similar error is encountered in accessing the file, an exception is thrown with a message indicating a file I/O error. IOErrorflash.errors:IOErrorThe size of the file in bytes. The size of the file on the local disk in bytes. If size is 0, an exception is thrown.

Note: In the initial version of ActionScript 3.0, the size property was defined as a uint object, which supported files with sizes up to about 4 GB. It is now implemented as a Number object to support larger files.

FileReference.browse()
type The file type.StringIf the FileReference.browse(), FileReferenceList.browse(), or FileReference.download() method was not called successfully, an exception is thrown with a message indicating that functions were called in the incorrect sequence or an earlier call was unsuccessful. In this case, the value of the type property is null. IllegalOperationErrorflash.errors:IllegalOperationErrorGets the type or extension of the file. The file type.

In Windows or Linux, this property is the file extension. On the Macintosh, this property is the four-character file type, which is only used in Mac OS versions prior to Mac OS X. If the FileReference object was not populated, a call to get the value of this property returns null.

For Windows, Linux, and Mac OS X, the file extension — the portion of the name property that follows the last occurrence of the dot (.) character — identifies the file type.

FileReference.extension
FileReferenceList The FileReferenceList class provides a means to let users select one or more files for uploading.Provides a means to upload one or more files. flash.events:EventDispatcher The FileReferenceList class provides a means to let users select one or more files for uploading. A FileReferenceList object represents a group of one or more local files on the user's disk as an array of FileReference objects. For detailed information and important considerations about FileReference objects and the FileReference class, which you use with FileReferenceList, see the FileReference class.

To work with the FileReferenceList class:

  • Instantiate the class: var myFileRef = new FileReferenceList();
  • Call the FileReferenceList.browse() method, which opens a dialog box that lets the user select one or more files for upload: myFileRef.browse();
  • After the browse() method is called successfully, the fileList property of the FileReferenceList object is populated with an array of FileReference objects.
  • Call FileReference.upload() on each element in the fileList array.

The FileReferenceList class includes a browse() method and a fileList property for working with multiple files. While a call to FileReferenceList.browse() is executing, SWF file playback pauses in stand-alone and external versions of Flash Player and in AIR for Linux and Mac OS X 10.1 and earlier.

The following example shows how you can use events to manage the upload of multiple files. The CustomFileReferenceList class extends FileReferenceList and includes a complete event, which is dispatched when each individual file in the FileReferenceList object is uploaded. The LIST_COMPLETE event in the FileReferenceListExample class is dispatched when all the files in the FileReferenceList object have been uploaded.

To run this example, place a script that is written to accept a file upload at http://www.[yourDomain].com/yourUploadHandlerScript.cfm. Based on the location of your SWF file and where you are uploading files to, you also might need to compile the SWF file with Local Playback Security set to Access Network Only or update Flash® Player security settings to allow this file network access. If your upload server is remote and you run this example from your desktop computer, your server must have a crossdomain.xml file.

package { import flash.display.Sprite; import flash.events.*; import flash.net.FileReference; import flash.net.FileReferenceList; public class FileReferenceListExample extends Sprite { public static var LIST_COMPLETE:String = "listComplete"; public function FileReferenceListExample() { initiateFileUpload(); } private function initiateFileUpload():void { var fileRef:CustomFileReferenceList = new CustomFileReferenceList(); fileRef.addEventListener(FileReferenceListExample.LIST_COMPLETE, listCompleteHandler); fileRef.browse(fileRef.getTypes()); } private function listCompleteHandler(event:Event):void { trace("listCompleteHandler"); } } } import flash.events.*; import flash.net.FileReference; import flash.net.FileReferenceList; import flash.net.FileFilter; import flash.net.URLRequest; class CustomFileReferenceList extends FileReferenceList { private var uploadURL:URLRequest; private var pendingFiles:Array; public function CustomFileReferenceList() { uploadURL = new URLRequest(); uploadURL.url = "http://www.[yourDomain].com/yourUploadHandlerScript.cfm"; initializeListListeners(); } private function initializeListListeners():void { addEventListener(Event.SELECT, selectHandler); addEventListener(Event.CANCEL, cancelHandler); } public function getTypes():Array { var allTypes:Array = new Array(); allTypes.push(getImageTypeFilter()); allTypes.push(getTextTypeFilter()); return allTypes; } private function getImageTypeFilter():FileFilter { return new FileFilter("Images (*.jpg, *.jpeg, *.gif, *.png)", "*.jpg;*.jpeg;*.gif;*.png"); } private function getTextTypeFilter():FileFilter { return new FileFilter("Text Files (*.txt, *.rtf)", "*.txt;*.rtf"); } private function doOnComplete():void { var event:Event = new Event(FileReferenceListExample.LIST_COMPLETE); dispatchEvent(event); } private function addPendingFile(file:FileReference):void { trace("addPendingFile: name=" + file.name); pendingFiles.push(file); file.addEventListener(Event.OPEN, openHandler); file.addEventListener(Event.COMPLETE, completeHandler); file.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler); file.addEventListener(ProgressEvent.PROGRESS, progressHandler); file.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler); file.upload(uploadURL); } private function removePendingFile(file:FileReference):void { for (var i:uint; i < pendingFiles.length; i++) { if (pendingFiles[i].name == file.name) { pendingFiles.splice(i, 1); if (pendingFiles.length == 0) { doOnComplete(); } return; } } } private function selectHandler(event:Event):void { trace("selectHandler: " + fileList.length + " files"); pendingFiles = new Array(); var file:FileReference; for (var i:uint = 0; i < fileList.length; i++) { file = FileReference(fileList[i]); addPendingFile(file); } } private function cancelHandler(event:Event):void { var file:FileReference = FileReference(event.target); trace("cancelHandler: name=" + file.name); } private function openHandler(event:Event):void { var file:FileReference = FileReference(event.target); trace("openHandler: name=" + file.name); } private function progressHandler(event:ProgressEvent):void { var file:FileReference = FileReference(event.target); trace("progressHandler: name=" + file.name + " bytesLoaded=" + event.bytesLoaded + " bytesTotal=" + event.bytesTotal); } private function completeHandler(event:Event):void { var file:FileReference = FileReference(event.target); trace("completeHandler: name=" + file.name); removePendingFile(file); } private function httpErrorHandler(event:Event):void { var file:FileReference = FileReference(event.target); trace("httpErrorHandler: name=" + file.name); } private function ioErrorHandler(event:Event):void { var file:FileReference = FileReference(event.target); trace("ioErrorHandler: name=" + file.name); } private function securityErrorHandler(event:Event):void { var file:FileReference = FileReference(event.target); trace("securityErrorHandler: name=" + file.name + " event=" + event.toString()); } }
FileReferenceselect Dispatched when the user selects one or more files to upload from the file-browsing dialog box.flash.events.Event.SELECTflash.events.Event Dispatched when the user selects one or more files to upload from the file-browsing dialog box. (This dialog box opens when you call the FileReferenceList.browse(), FileReference.browse(), or FileReference.download() methods.) When the user selects a file and confirms the operation (for example, by clicking Save), the FileReferenceList object is populated with FileReference objects that represent the files that the user selects. FileReferenceList.browse()cancel Dispatched when the user dismisses the file-browsing dialog box.flash.events.Event.CANCELflash.events.Event Dispatched when the user dismisses the file-browsing dialog box. (This dialog box opens when you call the FileReferenceList.browse(), FileReference.browse(), or FileReference.download() methods.) FileReferenceList.browse()FileReferenceList Creates a new FileReferenceList object. Creates a new FileReferenceList object. A FileReferenceList object contains nothing until you call the browse() method on it and the user selects one or more files. When you call browse() on the FileReference object, the fileList property of the object is populated with an array of FileReference objects. FileReferenceFileReferenceList.browse()browse Displays a file-browsing dialog box that lets the user select one or more local files to upload.Thrown for the following reasons: 1) Another FileReference or FileReferenceList browse session is in progress; only one file browsing session may be performed at a time. 2) A setting in the user's mms.cfg file prohibits this operation. IllegalOperationErrorflash.errors:IllegalOperationErrorIf the typeFilter array does not contain correctly formatted FileFilter objects, an exception is thrown. For details on correct filter formatting, see the FileFilter documentation. ArgumentErrorArgumentErrorIf the method is not called in response to a user action, such as a mouse event or keypress event. ErrorErrorReturns true if the parameters are valid and the file-browsing dialog box opens. BooleantypeFilterArraynullAn array of FileFilter instances used to filter the files that are displayed in the dialog box. If you omit this parameter, all files are displayed. For more information, see the FileFilter class. Displays a file-browsing dialog box that lets the user select local files to upload. Displays a file-browsing dialog box that lets the user select one or more local files to upload. The dialog box is native to the user's operating system.

In Flash Player 10 and later, you can call this method successfully only in response to a user event (for example, in an event handler for a mouse click or keypress event). Otherwise, calling this method results in Flash Player throwing an Error.

When you call this method and the user successfully selects files, the fileList property of this FileReferenceList object is populated with an array of FileReference objects, one for each file that the user selects. Each subsequent time that the FileReferenceList.browse() method is called, the FileReferenceList.fileList property is reset to the file(s) that the user selects in the dialog box.

Using the typeFilter parameter, you can determine which files the dialog box displays.

Only one FileReference.browse(), FileReference.download(), or FileReferenceList.browse() session can be performed at a time on a FileReferenceList object (because only one dialog box can be opened at a time).

FileReference.browse()FileReference classFileFilter classselectflash.events:EventInvoked when the user has successfully selected an item for upload from the dialog box. Invoked when the user has successfully selected an item for upload from the dialog box.cancelflash.events:EventInvoked when the user dismisses the dialog box by clicking Cancel or by closing it. Invoked when the user dismisses the dialog box by clicking Cancel or by closing it.
fileList An array of FileReference objects.ArrayAn array of FileReference objects. An array of FileReference objects.

When the FileReferenceList.browse() method is called and the user has selected one or more files from the dialog box that the browse() method opens, this property is populated with an array of FileReference objects, each of which represents the files the user selected. You can then use this array to upload each file with the FileReference.upload()method. You must upload one file at a time.

The fileList property is populated anew each time browse() is called on that FileReferenceList object.

The properties of FileReference objects are described in the FileReference class documentation.

FileReferenceFileReference.upload()FileReferenceList.browse()
NetworkInterface The NetworkInterface class describes a network interface.Object The NetworkInterface class describes a network interface.

You can get a list of network interfaces by calling the findInterfaces() method of a NetworkInfo object.

NetworkInfoInterfaceAddressactive Reports whether this interface is active.Boolean Reports whether this interface is active. addresses The list of the addresses bound to this network interface. The list of the addresses bound to this network interface. displayName The display name of this network interface.String The display name of this network interface. hardwareAddress The hardware address of this network interface.String The hardware address of this network interface.

The hardware address is typically the Media Access Control (MAC) address of the network adapter or interface card.

mtu The maximum transmission unit (MTU) of this network interface.int The maximum transmission unit (MTU) of this network interface.

If the mtu value is reported as -1, then the actual MTU is unknown.

name The name of this network interface.String The name of this network interface. parent The NetworkInterface object representing the parent interface (if this interface has a parent).flash.net:NetworkInterface The NetworkInterface object representing the parent interface (if this interface has a parent).

This interface could have a parent if it is a subinterface. The parent property is null if this interface has no parent.

subInterfaces The list of subinterfaces attached to this network interface. The list of subinterfaces attached to this network interface.

Subinterfaces are often virtual interfaces. The subInterfaces property is null if this interface has no subinterfaces.

SharedObjectFlushStatus The SharedObjectFlushStatus class provides values for the code returned from a call to the SharedObject.flush() method.Object The SharedObjectFlushStatus class provides values for the code returned from a call to the SharedObject.flush() method. SharedObject.flush()FLUSHED Indicates that the flush completed successfully.flushedString Indicates that the flush completed successfully. SharedObject.flush()PENDING Indicates that the user is being prompted to increase disk space for the shared object before the flush can occur.pendingString Indicates that the user is being prompted to increase disk space for the shared object before the flush can occur. SharedObject.flush()SecureSocket The SecureSocket class enables code to make socket connections utilizing the Secure Sockets Layer (SSL) and Transport Layer Security (TLS) protocols.flash.net:Socket The SecureSocket class enables code to make socket connections utilizing the Secure Sockets Layer (SSL) and Transport Layer Security (TLS) protocols.

AIR profile support: This feature is supported on all desktop operating systems, but is not supported on all AIR for TV devices. It is not supported on mobile devices. You can test for support at run time using the SecureSocket.isSupported property. See AIR Profile Support for more information regarding API support across multiple profiles.

The SSL/TLS protocols provide a mechanism by which the identity of a host can be authenticated via its certificate, and provides for encrypted communication over the socket. SSLv3 and TLSv1 are supported. Validation of the server certificate is performed using the trust store and certificate validation support of the client platform.

The SecureSocket class will only connect to servers with valid, trusted certificates. You cannot choose to connect to a server in spite of a problem with it's certificate. For example, there is no way to connect to a server with an expired certificate or a certificate that doesn't chain to a trusted root certificate even though the certificate would be valid otherwise.

The SecureSocket class is useful for performing encrypted communication to a trusted server. In other respects a SecureSocket object behaves like a regular Socket object.

To use the methods of the SecureSocket class, first use the constructor, new SecureSocket(), to create a SecureSocket object. When you connect to a server, the server certificate is validated. If the certificate is valid and trusted, the connection is established and the Socket dispatches a connect event. If the certificate cannot be validated, the Socket dispatches an IOError event.

Important: The Online Certificate Status Protocol (OCSP) is not supported by all operating systems. Users can also disable OCSP checking on individual computers. If OCSP is not supported or is disabled and a certificate does not contain the information necessary to check revocation using a Certificate Revocation List (CRL), then certificate revocation is not checked. The certificate is accepted if otherwise valid. This could allow a server to use a revoked certificate.

The following example illustrates how to create and connect a SecureSocket object. package { import flash.display.Sprite; import flash.errors.IOError; import flash.events.Event; import flash.events.IOErrorEvent; import flash.net.SecureSocket; public class SecureSocketExample extends Sprite { private var secureSocket:SecureSocket = new SecureSocket(); public function SecureSocketExample() { secureSocket.addEventListener( Event.CONNECT, onConnect ) secureSocket.addEventListener( IOErrorEvent.IO_ERROR, onError ); try { secureSocket.connect( "208.77.188.166", 443 ); } catch ( error:Error ) { trace ( error.toString() ); } } private function onConnect( event:Event ):void { trace("Connected."); } private function onError( error:IOErrorEvent ):void { trace( error.text + ", " + secureSocket.serverCertificateStatus ); } } }
Socket classsocketData Dispatched when a socket has received data.flash.events.ProgressEvent.SOCKET_DATAflash.events.ProgressEvent Dispatched when a socket has received data. Events of type socketData do not use the ProgressEvent.bytesTotal property. ioError Dispatched when an input or output error occurs that causes a send or receive operation to fail.flash.events.IOErrorEvent.IO_ERRORflash.events.IOErrorEvent Dispatched when an input or output error occurs that causes a send or receive operation to fail.

When a server certificate cannot be validated, the error event dispatched is an IOError. In this case, you can check the serverCertificateStatus property to determine the cause of the problem.

connect Dispatched when a network connection has been established.flash.events.Event.CONNECTflash.events.Event Dispatched when a network connection has been established. close Dispatched when the server closes the socket connection.flash.events.Event.CLOSEflash.events.Event Dispatched when the server closes the socket connection.

The close event is dispatched only when the server closes the connection; it is not dispatched when you call the SecureSocket.close() method.

SecureSocket Creates a new SecureSocket object.This error occurs when SSLv3 or TLSv1 support is not available. IllegalOperationErrorflash.errors:IllegalOperationError Creates a new SecureSocket object.

Check SecureSocket.isSupported before attempting to create a SecureSocket instance. If SSLv3 or TLSv1 sockets are not supported, the runtime will throw an IllegalOperationError.

connect Connects the socket to the specified host and port using SSL or TLS.No host was specified and the connection failed. IOErrorflash.errors:IOErrorThis error occurs if you specify a socket port less than zero or higher than 65535. SecurityErrorSecurityErrorhostStringThe name or IP address of the host to connect to. portintThe port number to connect to. Connects the socket to the specified host and port using SSL or TLS.

When you call the connect() method, the server certificate is validated. If the SSL/TLS handshake succeeds and the certificate is valid and trusted, the connection is established, the socket dispatches a connect event. If the handshake fails or the certificate cannot be validated, the socket dispatches an IOError event. You can check the certificate validation result by reading the serverCertificateStatus property after one of these events has been dispatched. (When a connect event is dispatched, the certificate status is always trusted.)

If the socket is already connected, the existing connection is closed first.

connectflash.events:EventDispatched when a network connection has been established. Dispatched when a network connection has been established.ioErrorflash.events:IOErrorEventDispatched if a host is specified and an input/output error occurs that causes the connection to fail. This includes SSL/TLS handshake errors and failure to successfully validate the host's server certificate. Dispatched if a host is specified and an input/output error occurs that causes the connection to fail.
isSupported Indicates whether the secure sockets are supported on the current system.Boolean Indicates whether the secure sockets are supported on the current system.

Secure sockets are not supported on all platforms. Check this property before attempting to create a new SecureSocket instance.

serverCertificateStatus The status of the server's certificate.String The status of the server's certificate.

The status is CertificateStatus.UNKNOWN until the socket attempts to connect to a server. After validation, the status will be one of the strings enumerated by the CertificateStatus class. The connection only succeeds when the certificate is valid and trusted. Thus, after a connect event, the status is always trusted.

Note: Once the certificate has been validated or rejected, the status value is not updated until the next call to the connect() method. Calling close() does not reset the status value to "unknown".

CertificateStatus class
ServerSocket The ServerSocket class allows code to act as a server for Transport Control Protocol (TCP) connections.flash.events:EventDispatcher The ServerSocket class allows code to act as a server for Transport Control Protocol (TCP) connections.

AIR profile support: This feature is supported on all desktop operating systems, but is not supported on mobile devices or AIR for TV devices. You can test for support at run time using the ServerSocket.isSupported property. See AIR Profile Support for more information regarding API support across multiple profiles.

A TCP server listens for incoming connections from remote clients. When a client attempts to connect, the ServerSocket dispatches a connect event. The ServerSocketConnectEvent object dispatched for the event provides a Socket object representing the TCP connection between the server and the client. Use this Socket object for subsequent communication with the connected client. You can get the client address and port from the Socket object, if needed.

Note: Your application is responsible for maintaining a reference to the client Socket object. If you don't, the object is eligible for garbage collection and may be destroyed by the runtime without warning.

To put a ServerSocket object into the listening state, call the listen() method. In the listening state, the server socket object dispatches connect events whenever a client using the TCP protocol attempts to connect to the bound address and port. The ServerSocket object continues to listen for additional connections until you call the close() method.

TCP connections are persistent — they exist until one side of the connection closes it (or a serious network failure occurs). Any data sent over the connection is broken into transmittable packets and reassembled on the other end. All packets are guaranteed to arrive (within reason) — any lost packets are retransmitted. In general, the TCP protocol manages the available network bandwidth better than the UDP protocol. Most AIR applications that require socket communications should use the ServerSocket and Socket classes rather than the DatagramSocket class.

The ServerSocket class can only be used in Adobe AIR applications and only in the application security sandbox.

For more information related to security, see the Flash Player Developer Center Topic: Security.

The following example creates a socket server. To use the server, bind the socket to a local port and then connect to that port from another application. The server only understands UTF-8 strings. package { import flash.display.Sprite; import flash.events.Event; import flash.events.MouseEvent; import flash.events.ProgressEvent; import flash.events.ServerSocketConnectEvent; import flash.net.ServerSocket; import flash.net.Socket; import flash.text.TextField; import flash.text.TextFieldType; import flash.utils.ByteArray; public class ServerSocketExample extends Sprite { private var serverSocket:ServerSocket = new ServerSocket(); private var clientSocket:Socket; private var localIP:TextField; private var localPort:TextField; private var logField:TextField; private var message:TextField; public function ServerSocketExample() { setupUI(); } private function onConnect( event:ServerSocketConnectEvent ):void { clientSocket = event.socket; clientSocket.addEventListener( ProgressEvent.SOCKET_DATA, onClientSocketData ); log( "Connection from " + clientSocket.remoteAddress + ":" + clientSocket.remotePort ); } private function onClientSocketData( event:ProgressEvent ):void { var buffer:ByteArray = new ByteArray(); clientSocket.readBytes( buffer, 0, clientSocket.bytesAvailable ); log( "Received: " + buffer.toString() ); } private function bind( event:Event ):void { if( serverSocket.bound ) { serverSocket.close(); serverSocket = new ServerSocket(); } serverSocket.bind( parseInt( localPort.text ), localIP.text ); serverSocket.addEventListener( ServerSocketConnectEvent.CONNECT, onConnect ); serverSocket.listen(); log( "Bound to: " + serverSocket.localAddress + ":" + serverSocket.localPort ); } private function send( event:Event ):void { try { if( clientSocket != null && clientSocket.connected ) { clientSocket.writeUTFBytes( message.text ); clientSocket.flush(); log( "Sent message to " + clientSocket.remoteAddress + ":" + clientSocket.remotePort ); } else log("No socket connection."); } catch ( error:Error ) { log( error.message ); } } private function log( text:String ):void { logField.appendText( text + "\n" ); logField.scrollV = logField.maxScrollV; trace( text ); } private function setupUI():void { localIP = createTextField( 10, 10, "Local IP", "0.0.0.0"); localPort = createTextField( 10, 35, "Local port", "0" ); createTextButton( 170, 60, "Bind", bind ); message = createTextField( 10, 85, "Message", "Lucy can't drink milk." ); createTextButton( 170, 110, "Send", send ); logField = createTextField( 10, 135, "Log", "", false, 200 ) this.stage.nativeWindow.activate(); } private function createTextField( x:int, y:int, label:String, defaultValue:String = '', editable:Boolean = true, height:int = 20 ):TextField { var labelField:TextField = new TextField(); labelField.text = label; labelField.type = TextFieldType.DYNAMIC; labelField.width = 100; labelField.x = x; labelField.y = y; var input:TextField = new TextField(); input.text = defaultValue; input.type = TextFieldType.INPUT; input.border = editable; input.selectable = editable; input.width = 280; input.height = height; input.x = x + labelField.width; input.y = y; this.addChild( labelField ); this.addChild( input ); return input; } private function createTextButton( x:int, y:int, label:String, clickHandler:Function ):TextField { var button:TextField = new TextField(); button.htmlText = "<u><b>" + label + "</b></u>"; button.type = TextFieldType.DYNAMIC; button.selectable = false; button.width = 180; button.x = x; button.y = y; button.addEventListener( MouseEvent.CLICK, clickHandler ); this.addChild( button ); return button; } } }
ServerSocketConnectEvent classSocket classXMLSocket classDatagramSocket classconnect Dispatched when a remote socket seeks to connect to this server socket.flash.events.ServerSocketConnectEvent.CONNECTflash.events.ServerSocketConnectEvent Dispatched when a remote socket seeks to connect to this server socket. close Dispatched when the operating system closes this socket.flash.events.Event.CLOSEflash.events.Event Dispatched when the operating system closes this socket.

The close event is not dispatched when the ServerSocket close() method is called. If other objects in your application rely on the close event, you can dispatch the event manually before calling the close() method.

ServerSocket Creates a ServerSocket object.This error occurs ff the calling content is running outside the AIR application security sandbox. SecurityErrorSecurityError Creates a ServerSocket object. bind Binds this socket to the specified local address and port.This error occurs when localPort is less than 0 or greater than 65535. RangeErrorRangeErrorThis error occurs when localAddress is not a syntactically well-formed IP address. ArgumentErrorArgumentErrorwhen the socket cannot be bound, such as when:
  • the underlying network socket (IP and port) is already in bound by another object or process.
  • the application is running under a user account that does not have the privileges necessary to bind to the port. Privilege issues typically occur when attempting to bind to well known ports (localPort < 1024)
  • this ServerSocket object is already bound. (Call close() before binding to a different socket.)
  • when localAddress is not a valid local address.
IOErrorflash.errors:IOError
localPortint0The number of the port to bind to on the local computer. If localPort, is set to 0 (the default), the next available system port is bound. Permission to connect to a port number below 1024 is subject to the system security policy. On Mac and Linux systems, for example, the application must be running with root privileges to connect to ports below 1024. localAddressString0.0.0.0The IP address on the local machine to bind to. This address can be an IPv4 or IPv6 address. If localAddress is set to 0.0.0.0 (the default), the socket listens on all available IPv4 addresses. To listen on all available IPv6 addresses, you must specify "::" as the localAddress argument. To use an IPv6 address, the computer and network must both be configured to support IPv6. Furthermore, a socket bound to an IPv4 address cannot connect to a socket with an IPv6 address. Likewise, a socket bound to an IPv6 address cannot connect to a socket with an IPv4 address. The type of address must match.
Binds this socket to the specified local address and port.
close Closes the socket and stops listening for connections.This error occurs if the socket could not be closed, or the socket was not open. ErrorError Closes the socket and stops listening for connections.

Closed sockets cannot be reopened. Create a new ServerSocket instance instead.

listen Initiates listening for TCP connections on the bound IP address and port.This error occurs if the socket is not open or bound. This error also occurs if the call to listen() fails for any other reason. IOErrorflash.errors:IOErrorThis error occurs if the backlog parameter is less than zero. RangeErrorRangeErrorbacklogint0The maximum length of the queue of pending connections. If backlog is 0, the queue length is set to the maximum system value. Initiates listening for TCP connections on the bound IP address and port.

The listen() method returns immediately. Once you call listen(), the ServerSocket object dispatches a connect event whenever a connection attempt is made. The socket property of the ServerSocketConnectEvent event object references a Socket object representing the server-client connection.

The backlog parameter specifies how many pending connections are queued while the connect events are processed by your application. If the queue is full, additional connections are denied without a connect event being dispatched. If the default value of zero is specified, then the system-maximum queue length is used. This length varies by platform and can be configured per computer. If the specified value exceeds the system-maximum length, then the system-maximum length is used instead. No means for discovering the actual backlog value is provided. (The system-maximum value is determined by the SOMAXCONN setting of the TCP network subsystem on the host computer.)

bound Indicates whether the socket is bound to a local address and port.Boolean Indicates whether the socket is bound to a local address and port. bind()isSupported Indicates whether or not ServerSocket features are supported in the run-time environment.Boolean Indicates whether or not ServerSocket features are supported in the run-time environment. listening Indicates whether the server socket is listening for incoming connections.Boolean Indicates whether the server socket is listening for incoming connections. listen()localAddress The IP address on which the socket is listening.String The IP address on which the socket is listening. bind()localPort The port on which the socket is listening.int The port on which the socket is listening. bind()
FileFilter The FileFilter class is used to indicate what files on the user's system are shown in the file-browsing dialog box that is displayed when the FileReference.browse() method, the FileReferenceList.browse() method is called or a browse method of a File, FileReference, or FileReferenceList object is called.Object The FileFilter class is used to indicate what files on the user's system are shown in the file-browsing dialog box that is displayed when the FileReference.browse() method, the FileReferenceList.browse() method is called or a browse method of a File, FileReference, or FileReferenceList object is called. FileFilter instances are passed as a value for the optional typeFilter parameter to the method. If you use a FileFilter instance, extensions and file types that aren't specified in the FileFilter instance are filtered out; that is, they are not available to the user for selection. If no FileFilter object is passed to the method, all files are shown in the dialog box.

You can use FileFilter instances in one of two ways:

  • A description with file extensions only
  • A description with file extensions and Macintosh file types

The two formats are not interchangeable within a single call to the browse method. You must use one or the other.

You can pass one or more FileFilter instances to the browse method, as shown in the following:

var imagesFilter:FileFilter = new FileFilter("Images", "~~.jpg;~~.gif;~~.png"); var docFilter:FileFilter = new FileFilter("Documents", "~~.pdf;~~.doc;~~.txt"); var myFileReference:FileReference = new FileReference(); myFileReference.browse([imagesFilter, docFilter]);

Or in an AIR application:

var imagesFilter:FileFilter = new FileFilter("Images", "~~.jpg;~~.gif;~~.png"); var docFilter:FileFilter = new FileFilter("Documents", "~~.pdf;~~.doc;~~.txt"); var myFile:File = new File(); myFile.browseForOpen("Open", [imagesFilter, docFilter]);

The list of extensions in the FileFilter.extension property is used to filter the files shown in the file browsing dialog. The list is not actually displayed in the dialog box; to display the file types for users, you must list the file types in the description string as well as in the extension list. The description string is displayed in the dialog box in Windows and Linux. (It is not used on the Macintosh®.) On the Macintosh, if you supply a list of Macintosh file types, that list is used to filter the files. If not, the list of file extensions is used.

FileFilter Creates a new FileFilter instance.descriptionStringThe description string that is visible to users when they select files for uploading. extensionStringA list of file extensions that indicate which file formats are visible to users when they select files for uploading. macTypeStringnullA list of Macintosh file types that indicate which file types are visible to users when they select files for uploading. If no value is passed, this parameter is set to null. Creates a new FileFilter instance. The following example uploads an image from your local file system to the root display object (in this case, the stage). Example provided by Andre Venancio. var buttonShape:Shape = new Shape(); buttonShape.graphics.beginFill(0x336699); buttonShape.graphics.drawCircle(50, 50, 25); var button = new SimpleButton(buttonShape, buttonShape, buttonShape, buttonShape); addChild(button); var fileRef:FileReference= new FileReference(); button.addEventListener(MouseEvent.CLICK, onButtonClick); function onButtonClick(e:MouseEvent):void { fileRef.browse([new FileFilter("Images", "*.jpg;*.gif;*.png")]); fileRef.addEventListener(Event.SELECT, onFileSelected); } function onFileSelected(e:Event):void { fileRef.addEventListener(Event.COMPLETE, onFileLoaded); fileRef.load(); } function onFileLoaded(e:Event):void { var loader:Loader = new Loader(); loader.loadBytes(e.target.data); addChild(loader); } description The description string for the filter.String The description string for the filter. The description is visible to the user in the dialog box that opens when FileReference.browse() or FileReferenceList.browse() is called. The description string contains a string, such as "Images (~~.gif, ~~.jpg, ~~.png)", that can help instruct the user on what file types can be uploaded or downloaded. Note that the actual file types that are supported by this FileReference object are stored in the extension property. extension A list of file extensions.String A list of file extensions. This list indicates the types of files that you want to show in the file-browsing dialog box. (The list is not visible to the user; the user sees only the value of the description property.) The extension property contains a semicolon-delimited list of file extensions, with a wildcard (~~) preceding each extension, as shown in the following string: "~~.jpg;~~.gif;~~.png". macType A list of Macintosh file types.String A list of Macintosh file types. This list indicates the types of files that you want to show in the file-browsing dialog box. (This list itself is not visible to the user; the user sees only the value of the description property.) The macType property contains a semicolon-delimited list of Macintosh file types, as shown in the following string: "JPEG;jp2_;GIFF".
URLRequest The URLRequest class captures all of the information in a single HTTP request.Object The URLRequest class captures all of the information in a single HTTP request. URLRequest objects are passed to the load() methods of the Loader, URLStream, and URLLoader classes, and to other loading operations, to initiate URL downloads. They are also passed to the upload() and download() methods of the FileReference class.

A SWF file in the local-with-filesystem sandbox may not load data from, or provide data to, a resource that is in the network sandbox.

By default, the calling SWF file and the URL you load must be in the same domain. For example, a SWF file at www.adobe.com can load data only from sources that are also at www.adobe.com. To load data from a different domain, place a URL policy file on the server hosting the data.

However, in Adobe AIR, content in the application security sandbox (content installed with the AIR application) is not restricted by these security limitations. For content running in Adobe AIR, files in the application security sandbox can access URLs using any of the following URL schemes:

  • http and https
  • file
  • app-storage
  • app

Content running in Adobe AIR that is not in the application security sandbox observes the same restrictions as content running in the browser (in Flash Player), and loading is governed by the content's domain and any permissions granted in URL policy files.

For more information related to security, see the Flash Player Developer Center Topic: Security.

The following example creates a new Loader object and passes it a URLRequest object that contains the path to an XML file. If the loading operation is successful, a complete event is dispatched and the data in the XML file traces to the output. Additional event handlers capture other events, including error events.

To run this example, place a file named XMLFile.xml in the same directory as your SWF file.

package { import flash.display.Sprite; import flash.events.*; import flash.net.*; public class URLRequestExample extends Sprite { public function URLRequestExample() { var loader:URLLoader = new URLLoader(); configureListeners(loader); var request:URLRequest = new URLRequest("XMLFile.xml"); try { loader.load(request); } catch (error:Error) { trace("Unable to load requested document."); } } private function configureListeners(dispatcher:IEventDispatcher):void { dispatcher.addEventListener(Event.COMPLETE, completeHandler); dispatcher.addEventListener(Event.OPEN, openHandler); dispatcher.addEventListener(ProgressEvent.PROGRESS, progressHandler); dispatcher.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler); dispatcher.addEventListener(HTTPStatusEvent.HTTP_STATUS, httpStatusHandler); dispatcher.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler); } private function completeHandler(event:Event):void { var loader:URLLoader = URLLoader(event.target); trace("completeHandler: " + loader.data); } private function openHandler(event:Event):void { trace("openHandler: " + event); } private function progressHandler(event:ProgressEvent):void { trace("progressHandler loaded:" + event.bytesLoaded + " total: " + event.bytesTotal); } private function securityErrorHandler(event:SecurityErrorEvent):void { trace("securityErrorHandler: " + event); } private function httpStatusHandler(event:HTTPStatusEvent):void { trace("httpStatusHandler: " + event); } private function ioErrorHandler(event:IOErrorEvent):void { trace("ioErrorHandler: " + event); } } }
FileReferenceURLRequestHeaderURLRequestDefaultsURLLoaderURLStreamHTMLLoader classURLRequest Creates a URLRequest object.urlStringnullThe URL to be requested. You can set the URL later by using the url property. Creates a URLRequest object. If System.useCodePage is true, the request is encoded using the system code page, rather than Unicode. If System.useCodePage is false, the request is encoded using Unicode, rather than the system code page. The following example shows how you can open new browser windows from Flash Player using the navigateToURL() method. Example provided by ActionScriptExamples.com. // Requires // - Button symbol on Stage (or a display object, such as a MovieClip) with instance name "buttonSymbol" // buttonSymbol.addEventListener(MouseEvent.CLICK, buttonSymbol_click); function buttonSymbol_click(evt:MouseEvent):void { var req:URLRequest = new URLRequest("http://www.adobe.com/"); navigateToURL(req, "_blank"); } flash.system.System.useCodePageauthenticate Specifies whether authentication requests should be handled (true or not (false) for this request.BooleanThe caller is not in the AIR application security sandbox. SecurityErrorSecurityErrortrue Specifies whether authentication requests should be handled or not. Specifies whether authentication requests should be handled (true or not (false) for this request. If false, authentication challenges return an HTTP error.

The supported authentication methods are:

  • Windows—HTTP Basic/Digest, Windows Integrated Authentication (including NTLM and Kerberos), SSL Certificate Authentication.
  • Mac—HTTP Basic/Digest, NTLM, SSL Certificate Authentication.

Note:The FileReference.upload(), FileReference.download(), and HTMLLoader.load() methods do not support the URLRequest.authenticate property.

flash.net.URLRequestDefaults.authenticate
cacheResponse Specifies whether successful response data should be cached for this request.BooleanThe caller is not in the AIR application security sandbox. SecurityErrorSecurityErrortrue Specifies whether successful response data should be cached for this request. When set to true, the AIR application uses the operating system's HTTP cache.

Note:The HTMLLoader.load() method does not support the URLRequest.cacheResponse property.

flash.net.URLRequestDefaults.cacheResponse
contentType The MIME content type of the content in the the data property.StringThe MIME content type of the content in the data property. The MIME content type of the content in the the data property.

The default value is application/x-www-form-urlencoded.

Note:The FileReference.upload(), FileReference.download(), and HTMLLoader.load() methods do not support the URLRequest.contentType property.

When sending a POST request, the values of the contentType and data properties must correspond properly. The value of the contentType property instructs servers on how to interpret the value of the data property.

  • If the value of the data property is a URLVariables object, the value of contentType must be application/x-www-form-urlencoded.
  • If the value of the data property is any other type, the value of contentType should indicate the type of the POST data that will be sent (which is the binary or string data contained in the value of the data property).
  • For FileReference.upload(), the Content-Type of the request is set automatically to multipart/form-data, and the value of the contentType property is ignored.

In Flash Player 10 and later, if you use a multipart Content-Type (for example "multipart/form-data") that contains an upload (indicated by a "filename" parameter in a "content-disposition" header within the POST body), the POST operation is subject to the security rules applied to uploads:

  • The POST operation must be performed in response to a user-initiated action, such as a mouse click or key press.
  • If the POST operation is cross-domain (the POST target is not on the same server as the SWF file that is sending the POST request), the target server must provide a URL policy file that permits cross-domain access.

Also, for any multipart Content-Type, the syntax must be valid (according to the RFC2046 standards). If the syntax appears to be invalid, the POST operation is subject to the security rules applied to uploads.

data
data An object containing data to be transmitted with the URL request.Object An object containing data to be transmitted with the URL request.

This property is used in conjunction with the method property. When the value of method is GET, the value of data is appended to the value of URLRequest.url, using HTTP query-string syntax. When the method value is POST (or any value other than GET), the value of data is transmitted in the body of the HTTP request.

The URLRequest API offers binary POST support and support for URL-encoded variables, as well as support for strings. The data object can be a ByteArray, URLVariables, or String object.

The way in which the data is used depends on the type of object used:

  • If the object is a ByteArray object, the binary data of the ByteArray object is used as POST data. For GET, data of ByteArray type is not supported. Also, data of ByteArray type is not supported for FileReference.upload() and FileReference.download().
  • If the object is a URLVariables object and the method is POST, the variables are encoded using x-www-form-urlencoded format and the resulting string is used as POST data. An exception is a call to FileReference.upload(), in which the variables are sent as separate fields in a multipart/form-data post.
  • If the object is a URLVariables object and the method is GET, the URLVariables object defines variables to be sent with the URLRequest object.
  • Otherwise, the object is converted to a string, and the string is used as the POST or GET data.

This data is not sent until a method, such as navigateToURL() or FileReference.upload(), uses the URLRequest object.

Note: The value of contentType must correspond to the type of data in the data property. See the note in the description of the contentType property.

The following example opens the remote application hosted at http://www.[yourDomain].com/application.jsp in a new browser window and passes data about a user session, captured in a URLVariables object, to the application.

Highlights of the example follow:

  1. The constructor function creates a URLRequest instance named request, taking the URL of the remote application as a parameter.
  2. A URLVariables object is created and two of its properties are assigned values.
  3. The URLVariables object is assigned to the data property of the URLRequest object.
  4. The example calls navigateToURL, which opens a new browser window to the remote application's URL.

Note: To run the example, the remote application URL in the example must be replaced with a working URL. Additionally, you would need server code to process the information captured by Flash Player in the URLVariables object.

package { import flash.display.Sprite; import flash.net.navigateToURL; import flash.net.URLRequest; import flash.net.URLVariables; public class URLVariablesExample extends Sprite { public function URLVariablesExample() { var url:String = "http://www.[yourDomain].com/application.jsp"; var request:URLRequest = new URLRequest(url); var variables:URLVariables = new URLVariables(); variables.exampleSessionId = new Date().getTime(); variables.exampleUserLabel = "guest"; request.data = variables; navigateToURL(request); } } }
URLRequest.methodURLRequestMethodURLVariablesflash.utils.ByteArraycontentType
digest A string that uniquely identifies the signed Adobe platform component to be stored to (or retrieved from) the Flash Player cache.StringThe digest provided does not match the digest of the file that is extracted from the downloaded signed file or the signed file loaded out of the cache. The application also throws this error if the provided digest is the wrong length or contains invalid (nonhexadecimal) characters. ArgumentErrorArgumentError A string that uniquely identifies the signed Adobe platform component to be stored to (or retrieved from) the Flash Player cache. An Adobe platform component is a signed file (a SWZ file) that contains SWF content that is cached persistently on a user's machine. All SWZ files are signed by Adobe. A digest corresponds to a single cached file; if you change the file in any way, its digest will change in an unpredictable way. By using a digest, you can verify the cached file across multiple domains. Two files with the same digest are the same file, and two files with different digests are not the same file. A file cannot (practically) be created to "spoof" a digest and pretend to be another digest.

The digest is based on an SHA-256 message digest algorithm (64 characters long in hexadecimal format).

For example, the Flex SDK includes a SWZ for the Flex framework (and it provides the digest string for that SWZ file). You can post this SWZ on your web server and load it in your SWF file (using the load() method of a URLLoader object). If the end user's machine already has the matching SWZ file cached, the application uses the cached SWZ file. (A SWZ file matches if its digest matches the one you provide.) Otherwise, the application downloads the SWZ file from the URL you specify.

Only set the digest parameter in a URLRequest object used in a call to the URLLoader.load() method to load a SWZ file. If the digest property of a a URLRequest object is set when it is used in other methods, the application throws an IOError exception.

The following example loads a remote file into the cache. At the end of the load, the byte array contains the actual file (not the signed file). The example completes the load operation by calling loadBytes(): var myURLReq:URLRequest = new URLRequest(); myURLReq.url = "http://yourdomain/users/jdoe/test01/_rsc/Automated/AssetCaching_rsc/test01/rsl.swz"; myURLReq.digest = "3B0AA28C7A990385E044D80F5637FB036317BB41E044D80F5637FB036317BB41"; var myURLLoader:URLLoader = new URLLoader(); myURLLoader.dataFormat = URLLoaderDataFormat.BINARY; myURLLoader.addEventListener("complete", onC); myURLLoad.load(myURLReq); function onC(e) { var someLoader:Loader = new Loader(); addChild(someLoader); someLoader.loadBytes((ByteArray)(myURLLoad.data)); }
followRedirects Specifies whether redirects are to be followed (true) or not (false).BooleanThe caller is not in the AIR application security sandbox. SecurityErrorSecurityErrortrue Specifies whether redirects are to be followed. Specifies whether redirects are to be followed (true) or not (false).

Note:The FileReference.upload(), FileReference.download(), and HTMLLoader.load() methods do not support the URLRequest.followRedirects property.

URLRequestDefaults.followRedirects
idleTimeout Specifies the idle timeout value (in milliseconds) for this request.NumberThe caller is not in the AIR application security sandbox. SecurityErrorSecurityErrorinitialized from the URLRequestDefaults.idleTimeout property Specifies the idle timeout value (in milliseconds) for this request.

The idle timeout is the amount of time the client waits for a response from the server, after the connection is established, before abandoning the request.

Note: The HTMLLoader.load() method does not support the URLRequest.idleTimeout property. The HTMLLoader class defines its own idleTimeout property.

URLRequestDefaults.idleTimeout
manageCookies Specifies whether the HTTP protocol stack should manage cookies for this request.BooleanThe caller is not in the AIR application security sandbox. SecurityErrorSecurityErrortrue Specifies whether the HTTP protocol stack should manage cookies for this request. When true, cookies are added to the request and response cookies are remembered. If false, cookies are not added to the request and response cookies are not remembered, but users can manage cookies themselves by direct header manipulation. Note: On Windows, you cannot add cookies to a URL request manually when manageCookies is set to true. On other operating systems, adding cookies to a request is permitted irrespective of whether manageCookies is set to true or false. When permitted, you can add cookies to a request manually by adding a URLRequestHeader object containing the cookie data to the requestHeaders array.

On Mac OS, cookies are shared with Safari. To clear cookies on Mac OS:

  1. Open Safari.
  2. Select Safari > Preferences, and click the Security panel.
  3. Click the Show Cookies button.
  4. Click the Reomove All button.

To clear cookies on Windows:

  1. Open the Internet Properties control panel, and click the General tab.
  2. Click the Delete Cookies button.
flash.net.URLRequestDefaults.manageCookies
method Controls the HTTP form submission method.StringIf the value parameter is not URLRequestMethod.GET or URLRequestMethod.POST. ArgumentErrorArgumentErrorURLRequestMethod.GET Controls the HTTP form submission method.

For SWF content running in Flash Player (in the browser), this property is limited to GET or POST operations, and valid values are URLRequestMethod.GET or URLRequestMethod.POST.

For content running in Adobe AIR, you can use any string value if the content is in the application security sandbox. Otherwise, as with content running in Flash Player, you are restricted to using GET or POST operations.

For content running in Adobe AIR, when using the navigateToURL() function, the runtime treats a URLRequest that uses the POST method (one that has its method property set to URLRequestMethod.POST) as using the GET method.

Note: If running in Flash Player and the referenced form has no body, Flash Player automatically uses a GET operation, even if the method is set to URLRequestMethod.POST. For this reason, it is recommended to always include a "dummy" body to ensure that the correct method is used.

The following example opens the remote application hosted at http://www.[yourDomain].com/application.jsp in a new browser window and passes data about a user session, captured in a URLVariables object, to the application. It explicitly sets the value of the URLRequest.method property to URLRequestMethod.POST.

Highlights of the example follow:

  1. The constructor function creates a URLRequest instance named request, taking the URL of the remote application as a parameter.
  2. A URLVariables object is created and two of its properties are assigned values.
  3. The URLVariables object is assigned to the data property of the URLRequest object.
  4. The value of the URLRequest.method property is set to URLRequestMethod.POST.
  5. The example calls navigateToURL, which opens a new browser window to the remote application's URL.

Note: To run the example, the remote application URL in the example must be replaced with a working URL. Additionally, you would need server code to process the information captured by Flash Player in the URLVariables object.

package { import flash.display.Sprite; import flash.net.navigateToURL; import flash.net.URLRequest; import flash.net.URLRequestMethod; import flash.net.URLVariables; public class URLRequest_method extends Sprite { public function URLRequest_method() { var url:String = "http://www.[yourDomain].com/application.jsp"; var request:URLRequest = new URLRequest(url); var variables:URLVariables = new URLVariables(); variables.exampleSessionId = new Date().getTime(); variables.exampleUserLabel = "guest"; request.data = variables; request.method = URLRequestMethod.POST; navigateToURL(request); } } }
URLRequestMethod class
requestHeaders The array of HTTP request headers to be appended to the HTTP request.Array The array of HTTP request headers to be appended to the HTTP request. The array is composed of URLRequestHeader objects. Each object in the array must be a URLRequestHeader object that contains a name string and a value string, as follows: var rhArray:Array = new Array(new URLRequestHeader("Content-Type", "text/html"));

Flash Player and the AIR runtime impose certain restrictions on request headers; for more information, see the URLRequestHeader class description.

Not all methods that accept URLRequest parameters support the requestHeaders property, consult the documentation for the method you are calling. For example, the FileReference.upload() and FileReference.download() methods do not support the URLRequest.requestHeaders property.

Due to browser limitations, custom HTTP request headers are only supported for POST requests, not for GET requests.

URLRequestHeader
url The URL to be requested.String The URL to be requested.

Be sure to encode any characters that are either described as unsafe in the Uniform Resource Locator specification (see http://www.faqs.org/rfcs/rfc1738.html) or that are reserved in the URL scheme of the URLRequest object (when not used for their reserved purpose). For example, use "%25" for the percent (%) symbol and "%23" for the number sign (#), as in "http://www.example.com/orderForm.cfm?item=%23B-3&discount=50%25".

By default, the URL must be in the same domain as the calling file, unless the content is running in the Adobe AIR application security sandbox. If you need to load data from a different domain, put a URL policy file on the server that is hosting the data. For more information, see the description of the URLRequest class.

For content running in Adobe AIR, files in the application security sandobx — files installed with the AIR application — can access URLs using any of the following URL schemes:

  • http and https
  • file
  • app-storage
  • app

Note: IPv6 (Internet Protocol version 6) is supported in AIR and in Flash Player 9.0.115.0 and later. IPv6 is a version of Internet Protocol that supports 128-bit addresses (an improvement on the earlier IPv4 protocol that supports 32-bit addresses). You might need to activate IPv6 on your networking interfaces. For more information, see the Help for the operating system hosting the data. If IPv6 is supported on the hosting system, you can specify numeric IPv6 literal addresses in URLs enclosed in brackets ([]), as in the following.

     rtmp://[2001:db8:ccc3:ffff:0:444d:555e:666f]:1935/test
     
The following example shows how you can dynamically load an image using the Loader class in ActionScript 3.0. Example provided by ActionScriptExamples.com. var url:String = "http://www.helpexamples.com/flash/images/image2.jpg"; var urlRequest:URLRequest = new URLRequest(url); var loader:Loader = new Loader(); loader.load(urlRequest); addChild(loader);
useCache Specifies whether the local cache should be consulted before this URLRequest fetches data.BooleanThe caller is not in the AIR application security sandbox. SecurityErrorSecurityErrortrue Specifies whether the local cache should be consulted before this URLRequest fetches data.

Note:The HTMLLoader.load() method does not support the URLRequest.useCache property.

flash.net.URLRequestDefaults.useCache
userAgent Specifies the user-agent string to be used in the HTTP request.StringThe caller is not in the AIR application security sandbox. SecurityErrorSecurityError Specifies the user-agent string to be used in the HTTP request.

The default value is the same user agent string that is used by Flash Player, which is different on Mac, Linux, and Windows.

Note: This property does not affect the user agent string when the URLRequest object is used with the load() method of an HTMLLoader object. To set the user agent string for an HTMLLoader object, set the userAgent property of the HTMLLoader object or set the static URLRequestDefaults.userAgent property.

flash.net.URLRequestDefaults.userAgentflash.html.HTMLLoader.userAgent
InterfaceAddress The InterfaceAddress class reports the properties of a network interface address.Object The InterfaceAddress class reports the properties of a network interface address. NetworkInfo classNetworkInterface classaddress The Internet Protocol (IP) address.String The Internet Protocol (IP) address. broadcast The broadcast address of the local network segment.String The broadcast address of the local network segment. ipVersion The IP address type (IPv4 or IPv6).String The IP address type (IPv4 or IPv6). prefixLength The prefix length for this address.int The prefix length for this address.

For IPv4 addresses, this is the subnet mask. Examples of the prefix length for IPv4 values include: 8 (255.0.0.0), 16 (255.255.0.0) and 24 (255.255.255.0). Example IPv6 prefix length values include 128 (::1/128) and 32 (2001:db8::/32)

Note: If the prefix length for this address is not available, the value of prefixLength is -1. A prefix value is not always returned by the network implementation of a specific client computer.

GroupSpecifier The GroupSpecifier class is used to construct the opaque groupspec strings that can be passed to NetStream and NetGroup constructors.Constructs the opaque groupspec strings passed to NetStream and NetGroup constructors. Object The GroupSpecifier class is used to construct the opaque groupspec strings that can be passed to NetStream and NetGroup constructors. A groupspec specifies an RTMFP Peer-to-Peer Group, including the capabilities, restrictions, and authorizations of the member using the groupspec.

By default, all capabilities are disabled, and peer-to-peer connections are allowed.

flash.net.NetGroupflash.net.NetStreamGroupSpecifier Creates a new GroupSpecifier object.if name is empty or null. ArgumentErrorArgumentErrornameStringA name for the Group on which all members must agree. Creates a new GroupSpecifier object. By default, all capabilities are disabled, and peer-to-peer connections are allowed. flash.net.NetGroupflash.net.NetStreamaddBootstrapPeer Causes the associated NetStream or NetGroup to make an initial neighbor connection to the specified peerID.peerIDStringThe peerID to which an initial neighbor connection should be made to bootstrap into the peer-to-peer mesh. Causes the associated NetStream or NetGroup to make an initial neighbor connection to the specified peerID. encodeBootstrapPeerIDSpec()flash.net.NetGroup.addMemberHint()flash.net.NetGroup.addNeighbor()addIPMulticastAddress Causes the associated NetStream or NetGroup to join the specified IP multicast group and listen to the specified UDP port.addressStringA String specifying the address of the IPv4 or IPv6 multicast group to join, optionally followed by a colon (":") and the UDP port number. If specifying an IPv6 address and a port, the IPv6 address must be enclosed in square brackets. Examples: "224.0.0.254", "224.0.0.254:30000", "ff03::ffff", "[ff03::ffff]:30000". portnullThe UDP port on which to receive IP multicast datagrams. If port is null, the UDP port must be specified in address. If not null, the UDP port must not be specified in address. sourceStringnullIf not null, a String specifying the source IP address of a source-specific multicast (SSM). Causes the associated NetStream or NetGroup to join the specified IP multicast group and listen to the specified UDP port. encodeIPMulticastAddressSpec()ipMulticastMemberUpdatesEnabledauthorizations Returns a string that represents passwords for IP multicast publishing and for posting.String Returns a string that represents passwords for IP multicast publishing and for posting. Append the string to an unauthorized groupspec to enable features for which passwords have been set. encodePostingAuthorization()encodePublishAuthorization()groupspecWithAuthorizations()groupspecWithoutAuthorizations()setPostingPassword()setPublishPassword()encodeBootstrapPeerIDSpec Encodes and returns a string that represents a bootstrap peerID.StringpeerIDStringThe peerID to which an initial neighbor connection should be made to bootstrap into the peer-to-peer mesh. Encodes and returns a string that represents a bootstrap peerID. If you append the string to a groupspec, the associated NetStream or NetGroup makes an initial neighbor connection to the specified peerID. addBootstrapPeer()flash.net.NetGroup.addMemberHint()flash.net.NetGroup.addNeighbor()encodeIPMulticastAddressSpec Encodes and returns a string that represents an IP multicast socket address.StringaddressStringA String indicating the address of the IPv4 or IPv6 multicast group to join, optionally followed by a colon (":") and the UDP port number. If specifying an IPv6 address and a port, the IPv6 address must be enclosed in square brackets. Examples: "224.0.0.254", "224.0.0.254:30000", "ff03::ffff", "[ff03::ffff]:30000". portnullThe UDP port on which to receive IP multicast datagrams. If port is null, the UDP port must be specified in address. If not null, the UDP port must not be specified in address. sourceStringnullIf not null, a String specifying the source IP address of a source-specific multicast (SSM). Encodes and returns a string that represents an IP multicast socket address. If you append the string to a groupspec, the associated NetStream or NetGroup joins the specified IP multicast group and listens to the specified UDP port. addIPMulticastAddress()ipMulticastMemberUpdatesEnabledencodePostingAuthorization Encodes and returns a string that represents a posting password.StringpasswordStringThe password to encode, which must match the posting password (if set) to enable NetGroup.post(). Encodes and returns a string that represents a posting password. When posting is password-protected, you can concatenate the string to a groupspec to enable posting. groupspecWithoutAuthorizations()setPostingPassword()flash.net.NetGroup.post()encodePublishAuthorization Encodes and returns a string that represents a multicast publishing password.StringpasswordStringThe password to encode, which must match the publish password (if set) to enable NetStream.publish(). Encodes and returns a string that represents a multicast publishing password. When multicast publishing is password-protected, you can concatenate the string to a groupspec to enable publishing. groupspecWithoutAuthorizations()setPublishPassword()flash.net.NetStream.publish()groupspecWithAuthorizations Returns the opaque groupspec string, including authorizations, that can be passed to NetStream and NetGroup constructors.String Returns the opaque groupspec string, including authorizations, that can be passed to NetStream and NetGroup constructors. authorizations()groupspecWithoutAuthorizations()setPostingPassword()setPublishPassword()toString()groupspecWithoutAuthorizations Returns the opaque groupspec string, without authorizations, that can be passed to NetStream and NetGroup constructors.StringReturns the opaque groupspec string, without authorizations, that can be passed to NetStream and NetGroup constructors. Returns the opaque groupspec string, without authorizations, that can be passed to NetStream and NetGroup constructors. authorizations()encodePostingAuthorization()encodePublishAuthorization()groupspecWithAuthorizations()makeUnique Adds a strong pseudorandom tag to the groupspec to make it unique.Adds a strong pseudorandom tag to the groupspec to make it unique. Adds a strong pseudorandom tag to the groupspec to make it unique. The opaque groupspec string must then be passed verbatim to other potential members of the Group if they are to successfully join. setPostingPassword Specifies whether a password is required to post in the NetGroup.passwordStringnullThe password that must be given to use NetGroup.post(). If null, no password is required to post. saltStringnullModifies the hash of the password to increase the difficulty of guessing it. For best security, this parameter should be set to a random value. Specifies whether a password is required to post in the NetGroup. encodePostingAuthorization()groupspecWithAuthorizations()groupspecWithoutAuthorizations()flash.net.NetGroup.post()setPublishPassword Specifies whether a password is required to publish a multicast stream in the NetStream.passwordStringnullThe password that must be given to use NetStream.publish(). If null, no password is required to publish. saltStringnullModifies the hash of the password to increase the difficulty of guessing it. For best security, this parameter should be set to a random value. Specifies whether a password is required to publish a multicast stream in the NetStream. encodePublishAuthorization()groupspecWithAuthorizations()groupspecWithoutAuthorizations()flash.net.NetStream.publish()toString Identical to the groupspecWithAuthorizations() method.StringIdentical to the groupspecWithAuthorizations() method. Identical to the groupspecWithAuthorizations() method. Convenience method to return the opaque groupspec string, including authorizations, that can be passed to NetStream and NetGroup constructors. groupspecWithAuthorizations()ipMulticastMemberUpdatesEnabled Specifies whether information about group membership can be exchanged on IP multicast sockets.Boolean Specifies whether information about group membership can be exchanged on IP multicast sockets. IP multicast servers may send group membership updates to help bootstrap P2P meshes or heal partitions. Peers may send membership updates on the LAN to help bootstrap LAN P2P meshes and to inform on-LAN neighbors in global meshes that other on-LAN neighbors exist. These updates can improve P2P performance. addIPMulticastAddress()peerToPeerDisabledmulticastEnabled Specifies whether streaming is enabled for the NetGroup.Boolean Specifies whether streaming is enabled for the NetGroup. Methods used for streaming are NetStream.publish(), NetStream.play(), and NetStream.play2(). By default, this property is FALSE (streaming is disabled). setPublishPassword()flash.net.NetStream.play()flash.net.NetStream.play2()flash.net.NetStream.publish()objectReplicationEnabled Specifies whether object replication is enabled for the NetGroup.Boolean Specifies whether object replication is enabled for the NetGroup. By default, this property is FALSE (object replication is disabled). flash.net.NetGroup.addHaveObjects()flash.net.NetGroup.addWantObjects()flash.net.NetGroup.denyRequestedObject()flash.net.NetGroup.removeHaveObjects()flash.net.NetGroup.removeWantObjects()flash.net.NetGroup.writeRequestedObject()peerToPeerDisabled Specifies whether peer-to-peer connections are disabled for the NetGroup or NetStream.Boolean Specifies whether peer-to-peer connections are disabled for the NetGroup or NetStream. By default, this property is FALSE (P2P connections are enabled).

If P2P connections are disabled (you set this property to TRUE), the P2P warning dialog is suppressed. In this situation, no neighbor connections can be made, and no group members use upstream bandwidth. Disabling P2P connections in this way is generally useful only when receiving multicast streams via pure IP multicast.

postingEnabled Specifies whether posting is enabled for the NetGroup.Boolean Specifies whether posting is enabled for the NetGroup. By default, this property is FALSE (posting is disabled). flash.net.NetGroup.post()routingEnabled Specifies whether directed routing methods are enabled for the NetGroup.Boolean Specifies whether directed routing methods are enabled for the NetGroup. By default, this property is FALSE (directed routing methods are disabled). flash.net.NetGroup.sendToNearest()serverChannelEnabled Specifies whether members of the NetGroup can open a channel to the server.Boolean Specifies whether members of the NetGroup can open a channel to the server. By default, this property is FALSE.

A channel to the server must be opened before the server can provide supporting functions to group members. Depending on server configuration, supporting functions may or may not be provided over this channel.

LocalConnection The LocalConnection class lets you create a LocalConnection object that can invoke a method in another LocalConnection object.flash.events:EventDispatcher The LocalConnection class lets you create a LocalConnection object that can invoke a method in another LocalConnection object. The communication can be:
  • Within a single SWF file
  • Between multiple SWF files
  • Between content (SWF-based or HTML-based) in AIR applications
  • Between content (SWF-based or HTML-based) in an AIR application and SWF content running in a browser

AIR profile support: This feature is supported on all desktop operating systems and on all AIR for TV devices, but is not supported on mobile devices. You can test for support at run time using the LocalConnection.isSupported property. See AIR Profile Support for more information regarding API support across multiple profiles.

Note: AIR for TV devices support communication only between SWF-based content in AIR applications.

Local connections enable this kind of communication between SWF files without the use of fscommand() or JavaScript. LocalConnection objects can communicate only among files that are running on the same client computer, but they can be running in different applications — for example, a file running in a browser and a SWF file running in Adobe AIR.

LocalConnection objects created in ActionScript 3.0 can communicate with LocalConnection objects created in ActionScript 1.0 or 2.0. The reverse is also true: LocalConnection objects created in ActionScript 1.0 or 2.0 can communicate with LocalConnection objects created in ActionScript 3.0. Flash Player handles this communication between LocalConnection objects of different versions automatically.

There are three ways to add callback methods to a LocalConnection object:

  • Subclass the LocalConnection class and add methods.
  • Set the LocalConnection.client property to an object that implements the methods.
  • Create a dynamic class that extends LocalConnection and dynamically attach methods.

To understand how to use LocalConnection objects to implement communication between two files, it is helpful to identify the commands used in each file. One file is called the receiving file; it is the file that contains the method to be invoked. The receiving file must contain a LocalConnection object and a call to the connect() method. The other file is called the sending file; it is the file that invokes the method. The sending file must contain another LocalConnection object and a call to the send() method.

Your use of send() and connect() differs depending on whether the files are in the same domain, in different domains with predictable domain names, or in different domains with unpredictable or dynamic domain names. The following paragraphs explain the three different situations, with code samples for each.

Same domain. This is the simplest way to use a LocalConnection object, to allow communication only between LocalConnection objects that are located in the same domain, because same-domain communication is permitted by default. When two files from the same domain communicate, you do not need to implement any special security measures, and you simply pass the same value for the connectionName parameter to both the connect() and send() methods:

// receivingLC is in http://www.domain.com/receiving.swf receivingLC.connect('myConnection'); // sendingLC is in http://www.domain.com/sending.swf // myMethod() is defined in sending.swf sendingLC.send('myConnection', 'myMethod');

Different domains with predictable domain names. When two SWF files from different domains communicate, you need to allow communication between the two domains by calling the allowDomain() method. You also need to qualify the connection name in the send() method with the receiving LocalConnection object's domain name:

// receivingLC is in http://www.domain.com/receiving.swf receivingLC.allowDomain('www.anotherdomain.com'); receivingLC.connect('myConnection'); // sendingLC is in http://www.anotherdomain.com/sending.swf sendingLC.send('www.domain.com:myConnection', 'myMethod');

Different domains with unpredictable domain names. Sometimes, you might want to make the file with the receiving LocalConnection object more portable between domains. To avoid specifying the domain name in the send() method, but to indicate that the receiving and sending LocalConnection objects are not in the same domain, precede the connection name with an underscore (_), in both the connect() and send() calls. To allow communication between the two domains, call the allowDomain() method and pass the domains from which you want to allow LocalConnection calls. Alternatively, pass the wildcard (~~) argument to allow calls from all domains:

// receivingLC is in http://www.domain.com/receiving.swf receivingLC.allowDomain('~~'); receivingLC.connect('_myConnection'); // sendingLC is in http://www.anotherdomain.com/sending.swf sendingLC.send('_myConnection', 'myMethod');

From Flash Player to an AIR application. A LocalConnection object created in the AIR application sandbox uses a special string as it's connection prefix instead of a domain name. This string has the form: app#appID.pubID where appID is the application ID and pubID is the publisher ID of the application. (Only include the publisher ID if the AIR application uses a publisher ID.) For example, if an AIR application has an application ID of, "com.example", and no publisher ID, you could use: app#com.example:myConnection as the local connection string. The AIR application also must call the allowDomain() method, passing in the calling SWF file's domain of origin:

// receivingLC is an AIR application with app ID = com.example (and no publisher ID) receivingLC.allowDomain('www.domain.com'); receivingLC.connect('myConnection'); // sendingLC is in http://www.domain.com/sending.swf sendingLC.send('app#com.example:myConnection', 'myMethod');

Note: If an AIR application loads a SWF outside the AIR application sandbox, then the rules for establishing a local connection with that SWF are the same as the rules for establishing a connection with a SWF running in Flash Player.

From an AIR application to Flash Player. When an AIR application communicates with a SWF running in the Flash Player runtime, you need to allow communication between the two by calling the allowDomain() method and passing in the AIR application's connection prefix. For example, if an AIR application has an application ID of, "com.example", and no publisher ID, you could pass the string: app#com.example to the allowDomain() method. You also need to qualify the connection name in the send() method with the receiving LocalConnection object's domain name (use "localhost" as the domain for SWF files loaded from the local file system):

// receivingLC is in http://www.domain.com/receiving.swf receivingLC.allowDomain('app#com.example'); receivingLC.connect('myConnection'); // sendingLC is an AIR application with app ID = com.example (and no publisher ID) sendingLC.send('www.domain.com:myConnection', 'myMethod');

From an AIR application to another AIR application. To communicate between two AIR applications, you need to allow communication between the two by calling the allowDomain() method and passing in the sending AIR application's connection prefix. For example, if the sending application has an application ID of, "com.example", and no publisher ID, you could pass the string: app#com.example to the allowDomain() method in the receiving application. You also need to qualify the connection name in the send() method with the receiving LocalConnection object's connection prefix:

// receivingLC is an AIR application with app ID = com.sample (and no publisher ID) receivingLC.allowDomain('app#com.example'); receivingLC.connect('myConnection'); // sendingLC is an AIR application with app ID = com.example (and no publisher ID) sendingLC.send('app#com.sample:myConnection', 'myMethod');

You can use LocalConnection objects to send and receive data within a single file, but this is not a typical implementation.

For more information about the send() and connect() methods, see the discussion of the connectionName parameter in the LocalConnection.send() and LocalConnection.connect()entries. Also, see the allowDomain() and domain entries.

This example consists of two ActionScript classes which should be compiled into two separate SWF files:

In the LocalConnectionSenderExample SWF file, a LocalConnection instance is created, and when the button is pressed the call() method is used to call the method named lcHandler in the SWF file with the connection name "myConnection," passing the contents of the TextField as a parameter.

In the LocalConnectionReceiverExample SWF file, a LocalConnection instance is created and the connect() method is called to designate this SWF file as the recipient of messages that are addressed to the connection named "myConnection." In addition, this class includes a public method named lcHandler(); this method is the one that is called by the LocalConnectionSenderExample SWF file. When it's called, the text that is passed in as a parameter is appended to the TextField on the Stage.

Note: To test the example, both SWF files must be loaded on the same computer simultaneously.

// Code in LocalConnectionSenderExample.as package { import flash.display.Sprite; import flash.events.MouseEvent; import flash.net.LocalConnection; import flash.text.TextField; import flash.text.TextFieldType; import flash.events.StatusEvent; import flash.text.TextFieldAutoSize; public class LocalConnectionSenderExample extends Sprite { private var conn:LocalConnection; // UI elements private var messageLabel:TextField; private var message:TextField; private var sendBtn:Sprite; public function LocalConnectionSenderExample() { buildUI(); sendBtn.addEventListener(MouseEvent.CLICK, sendMessage); conn = new LocalConnection(); conn.addEventListener(StatusEvent.STATUS, onStatus); } private function sendMessage(event:MouseEvent):void { conn.send("myConnection", "lcHandler", message.text); } private function onStatus(event:StatusEvent):void { switch (event.level) { case "status": trace("LocalConnection.send() succeeded"); break; case "error": trace("LocalConnection.send() failed"); break; } } private function buildUI():void { const hPadding:uint = 5; // messageLabel messageLabel = new TextField(); messageLabel.x = 10; messageLabel.y = 10; messageLabel.text = "Text to send:"; messageLabel.autoSize = TextFieldAutoSize.LEFT; addChild(messageLabel); // message message = new TextField(); message.x = messageLabel.x + messageLabel.width + hPadding; message.y = 10; message.width = 120; message.height = 20; message.background = true; message.border = true; message.type = TextFieldType.INPUT; addChild(message); // sendBtn sendBtn = new Sprite(); sendBtn.x = message.x + message.width + hPadding; sendBtn.y = 10; var sendLbl:TextField = new TextField(); sendLbl.x = 1 + hPadding; sendLbl.y = 1; sendLbl.selectable = false; sendLbl.autoSize = TextFieldAutoSize.LEFT; sendLbl.text = "Send"; sendBtn.addChild(sendLbl); sendBtn.graphics.lineStyle(1); sendBtn.graphics.beginFill(0xcccccc); sendBtn.graphics.drawRoundRect(0, 0, (sendLbl.width + 2 + hPadding + hPadding), (sendLbl.height + 2), 5, 5); sendBtn.graphics.endFill(); addChild(sendBtn); } } }
// Code in LocalConnectionReceiverExample.as package { import flash.display.Sprite; import flash.net.LocalConnection; import flash.text.TextField; public class LocalConnectionReceiverExample extends Sprite { private var conn:LocalConnection; private var output:TextField; public function LocalConnectionReceiverExample() { buildUI(); conn = new LocalConnection(); conn.client = this; try { conn.connect("myConnection"); } catch (error:ArgumentError) { trace("Can't connect...the connection name is already being used by another SWF"); } } public function lcHandler(msg:String):void { output.appendText(msg + "\n"); } private function buildUI():void { output = new TextField(); output.background = true; output.border = true; output.wordWrap = true; addChild(output); } } }
flash.net.LocalConnection.send()flash.net.LocalConnection.allowDomain()flash.net.LocalConnection.domainstatus Dispatched when a LocalConnection object reports its status.flash.events.StatusEvent.STATUSflash.events.StatusEvent Dispatched when a LocalConnection object reports its status. If LocalConnection.send() is successful, the value of the status event object's level property is "status"; if the call fails, the level property is "error". If the receiving file refuses the connection, the call can fail without notification to the sending file. LocalConnection.send()securityError Dispatched if a call to LocalConnection.send() attempts to send data to a different security sandbox.flash.events.SecurityErrorEvent.SECURITY_ERRORflash.events.SecurityErrorEvent Dispatched if a call to LocalConnection.send() attempts to send data to a different security sandbox. send()asyncError Dispatched when an exception is thrown asynchronously &#x2014; that is, from native asynchronous code.flash.events.AsyncErrorEvent.ASYNC_ERRORflash.events.AsyncErrorEvent Dispatched when an exception is thrown asynchronously — that is, from native asynchronous code. LocalConnection Creates a LocalConnection object. Creates a LocalConnection object. You can use LocalConnection objects to enable communication between different files that are running on the same client computer. flash.net.LocalConnection.connect()flash.net.LocalConnection.send()allowDomain Specifies one or more domains that can send LocalConnection calls to this LocalConnection instance.All parameters specified must be non-null strings. ArgumentErrorArgumentErrordomainsOne or more strings that name the domains from which you want to allow LocalConnection calls. This parameter has two special cases:
  • You can specify a wildcard character "~~" to allow calls from all domains.
  • You can specify the string "localhost" to allow calls to this file from files that are installed locally. Flash Player 8 introduced security restrictions on local files. By default, a SWF file running in Flash Player that is allowed to access the Internet cannot also have access to the local file system. In Flash Player, if you specify "localhost", any local SWF file can access this SWF file.
Specifies one or more domains that can send LocalConnection calls to this LocalConnection instance.

You cannot use this method to let files hosted using a secure protocol (HTTPS) allow access from files hosted in nonsecure protocols; you must use the allowInsecureDomain() method instead.

You may want to use this method so that a child file from a different domain can make LocalConnection calls to the parent file, without knowing the final domain from which the child file will come. This can happen, for example, when you use load-balancing redirects or third-party servers. In this situation, you can use the url property of the LoaderInfo object used with the load, to get the domain to use with the allowDomain() method. For example, if you use a Loader object to load a child file, once the file is loaded, you can check the contentLoaderInfo.url property of the Loader object, and parse the domain out of the full URL string. If you do this, make sure that you wait until the file is loaded, because the contentLoaderInfo.url property will not have its final, correct value until the file is completely loaded.

The opposite situation can also occur: you might create a child file that wants to accept LocalConnection calls from its parent but doesn't know the domain of its parent. In this situation, implement this method by checking whether the domain argument matches the domain of the loaderInfo.url property in the loaded file. Again, you must parse the domain out of the full URL from loaderInfo.url. In this situation, you don't have to wait for the parent file to load; the parent will already be loaded by the time the child loads.

When using this method, consider the Flash Player security model. By default, a LocalConnection object is associated with the sandbox of the file that created it, and cross-domain calls to LocalConnection objects are not allowed unless you call the LocalConnection.allowDomain() method in the receiving file. However, in Adobe AIR, content in the application security sandbox (content installed with the AIR application) are not restricted by these security limitations.

For more information related to security, see the Flash Player Developer Center Topic: Security.

Note: The allowDomain() method has changed from the form it had in ActionScript 1.0 and 2.0. In those earlier versions, allowDomain was a callback method that you implemented. In ActionScript 3.0, allowDomain() is a built-in method of LocalConnection that you call. With this change, allowDomain() works in much the same way as flash.system.Security.allowDomain().

flash.net.LocalConnection.allowInsecureDomain()flash.display.LoaderInfo.urlflash.system.Security.allowDomain()
allowInsecureDomain Specifies one or more domains that can send LocalConnection calls to this LocalConnection object.All parameters specified must be non-null strings. ArgumentErrorArgumentErrordomainsOne or more strings that name the domains from which you want to allow LocalConnection calls. There are two special cases for this parameter:
  • You can specify the wildcard character "~~" to allow calls from all domains. Specifying "~~" does not include local hosts.
  • You can specify the string "localhost" to allow calls to this SWF file from SWF files that are installed locally. 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 this SWF file. Remember that you must also designate the calling SWF file as a local-with-networking SWF file at authoring time.
Specifies one or more domains that can send LocalConnection calls to this LocalConnection object.

The allowInsecureDomain() method works just like the allowDomain() method, except that the allowInsecureDomain() method additionally permits SWF files from non-HTTPS origins to send LocalConnection calls to files from HTTPS origins. This difference is meaningful only if you call the allowInsecureDomain() method from a file that was loaded using HTTPS. You must call the allowInsecureDomain() method even if you are crossing a non-HTTPS/HTTPS boundary within the same domain; by default, LocalConnection calls are never permitted from non-HTTPS files to HTTPS files, even within the same domain.

Calling allowInsecureDomain() is not recommended, because it can compromise the security offered by HTTPS. When you load a file over HTTPS, you can be reasonably sure that the file will not be tampered with during delivery over the network. If you then permit a non-HTTPS file to make LocalConnection calls to the HTTPS file, you are accepting calls from a file that may in fact have been tampered with during delivery. This generally requires extra vigilance because you cannot trust the authenticity of LocalConnection calls arriving at your HTTPS file.

By default, files hosted using the HTTPS protocol can be accessed only by other files hosted using the HTTPS protocol. This implementation maintains the integrity provided by the HTTPS protocol.

Using this method to override the default behavior is not recommended, because it compromises HTTPS security. However, you might need to do so, for example, if you need to permit access to HTTPS SWF files published for Flash Player 9 or later from HTTP files SWF published for Flash Player 6 or earlier.

For more information related to security, see the Flash Player Developer Center Topic: Security.

flash.net.LocalConnection.allowDomain()
close Closes (disconnects) a LocalConnection object.The LocalConnection instance is not connected, so it cannot be closed. ArgumentErrorArgumentError Closes (disconnects) a LocalConnection object. Issue this command when you no longer want the object to accept commands — for example, when you want to issue a connect() command using the same connectionName parameter in another SWF file. flash.net.LocalConnection.connect()connect Prepares a LocalConnection object to receive commands that are sent from a send() command (from the sending LocalConnection object).The value passed to the connectionName parameter must be non-null. TypeErrorTypeErrorThis error can occur for three reasons: 1) The string value passed to the connectionName parameter was null. Pass a non-null value. 2) The value passed to the connectionName parameter contained a colon (:). Colons are used as special characters to separate the superdomain from the connectionName string in the send() method, not the connect()method. 3) The LocalConnection instance is already connected. ArgumentErrorArgumentErrorconnectionNameStringA string that corresponds to the connection name specified in the send() command that wants to communicate with the receiving LocalConnection object. Prepares a LocalConnection object to receive commands that are sent from a send() command (from the sending LocalConnection object). The object used with the connect() method is called the receiving LocalConnection object. The receiving and sending objects must be running on the same client computer.

To avoid a race condition, define the methods attached to the receiving LocalConnection object before calling this method, as shown in the LocalConnection class example.

By default, the connectionName argument is resolved into a value of "superdomain:connectionName", where superdomain is the superdomain of the file that contains the connect() command. For example, if the file that contains the receiving LocalConnection object is located at www.someDomain.com, connectionName resolves to "someDomain.com:connectionName". (If a file running in Flash Player is located on the client computer, the value assigned to superdomain is "localhost".)

In content running in the application security sandbox in Adobe AIR (content installed with the AIR application), the runtime uses the string app# followed by the application ID for the AIR application (defined in the application descriptor file) in place of the superdomain. For example a connectionName for an application with the application ID com.example.air.MyApp connectionName resolves to "app#com.example.air.MyApp:connectionName".

Also by default, Flash Player lets the receiving LocalConnection object accept commands only from sending LocalConnection objects whose connection name also resolves into a value of "superdomain:connectionName". In this way, Flash Player makes it simple for files that are located in the same domain to communicate with each other.

If you are implementing communication only between files in the same domain, specify a string for connectionName that does not begin with an underscore (_) and that does not specify a domain name (for example, "myDomain:connectionName"). Use the same string in the connect(connectionName) method.

If you are implementing communication between files in different domains, specifying a string for connectionName that begins with an underscore (_) makes the file with the receiving LocalConnection object more portable between domains. Here are the two possible cases:

  • If the string for connectionNamedoes not begin with an underscore (_), a prefix is added with the superdomain and a colon (for example, "myDomain:connectionName"). Although this ensures that your connection does not conflict with connections of the same name from other domains, any sending LocalConnection objects must specify this superdomain (for example, "myDomain:connectionName"). If the file with the receiving LocalConnection object is moved to another domain, the player changes the prefix to reflect the new superdomain (for example, "anotherDomain:connectionName"). All sending LocalConnection objects would have to be manually edited to point to the new superdomain.
  • If the string for connectionNamebegins with an underscore (for example, "_connectionName"), a prefix is not added to the string. This means that the receiving and sending LocalConnection objects use identical strings for connectionName. If the receiving object uses allowDomain() to specify that connections from any domain will be accepted, the file with the receiving LocalConnection object can be moved to another domain without altering any sending LocalConnection objects.

For more information, see the discussion in the class overview and the discussion of connectionName in send(), and also the allowDomain() and domain entries.

Note: Colons are used as special characters to separate the superdomain from the connectionName string. A string for connectionName that contains a colon is not valid.

When you use this method , consider the Flash Player security model. By default, a LocalConnection object is associated with the sandbox of the file that created it, and cross-domain calls to LocalConnection objects are not allowed unless you call the LocalConnection.allowDomain() method in the receiving file. You can prevent a file from using this method by setting the allowNetworking parameter of the the object and embed tags in the HTML page that contains the SWF content. However, in Adobe AIR, content in the application security sandbox (content installed with the AIR application) are not restricted by these security limitations.

For more information related to security, see the Flash Player Developer Center Topic: Security.

flash.net.LocalConnection.send()flash.net.LocalConnection.allowDomain()flash.net.LocalConnection.domain
send Invokes the method named methodName on a connection that was opened with the connect(connectionName) method (in the receiving LocalConnection object).The value of either connectionName or methodName is null. Pass non-null values for these parameters. TypeErrorTypeErrorThis error can occur for one of the following reasons: 1) The value of either connectionName or methodName is an empty string. Pass valid strings for these parameters. 2) The method specified in methodName is restricted. 3) The serialized message that is being sent is too large (larger than 40K). ArgumentErrorArgumentErrorconnectionNameStringCorresponds to the connection name specified in the connect() command that wants to communicate with the sending LocalConnection object. methodNameStringThe name of the method to be invoked in the receiving LocalConnection object. The following method names cause the command to fail: send, connect, close, allowDomain, allowInsecureDomain, client, and domain. argumentsAdditional optional parameters to be passed to the specified method. Invokes the method named methodName on a connection that was opened with the connect(connectionName) method (in the receiving LocalConnection object). The object used with the send() method is called the sending LocalConnection object. The SWF files that contain the sending and receiving objects must be running on the same client computer.

There is a 40 kilobyte limit to the amount of data you can pass as parameters to this command. If send() throws an ArgumentError but your syntax is correct, try dividing the send() requests into multiple commands, each with less than 40K of data.

As discussed in the connect() entry, the current superdomain in added to connectionName by default. If you are implementing communication between different domains, you need to define connectionName in both the sending and receiving LocalConnection objects in such a way that the current superdomain is not added to connectionName. You can do this in one of the following two ways:

  • Use an underscore (_) at the beginning of connectionName in both the sending and receiving LocalConnection objects. In the file that contains the receiving object, use LocalConnection.allowDomain() to specify that connections from any domain will be accepted. This implementation lets you store your sending and receiving files in any domain.
  • Include the superdomain in connectionName in the sending LocalConnection object — for example, myDomain.com:myConnectionName. In the receiving object, use LocalConnection.allowDomain() to specify that connections from the specified superdomain will be accepted (in this case, myDomain.com) or that connections from any domain will be accepted.

Note: You cannot specify a superdomain in connectionName in the receiving LocalConnection object — you can do this in only the sending LocalConnection object.

When you use this method , consider the Flash Player security model. By default, a LocalConnection object is associated with the sandbox of the file that created it, and cross-domain calls to LocalConnection objects are not allowed unless you call the LocalConnection.allowDomain() method in the receiving file. For SWF content running in the browser, ou can prevent a file from using this method by setting the allowNetworking parameter of the the object and embed tags in the HTML page that contains the SWF content. However, in Adobe AIR, content in the application security sandbox (content installed with the AIR application) are not restricted by these security limitations.

For more information related to security, see the Flash Player Developer Center Topic: Security.

flash.net.LocalConnection.allowDomain()flash.net.LocalConnection.connect()flash.net.LocalConnection.domainsecurityErrorflash.events:SecurityErrorEventLocalConnection.send() attempted to communicate with a SWF file from a security sandbox to which the calling code does not have access. You can work around this in the receiver's implementation of LocalConnection.allowDomain(). LocalConnection.send() attempted to communicate with a SWF file from a security sandbox to which the calling code does not have access.statusflash.events:StatusEventIf the value of the level property is "status", the call was successful; if the value is "error", the call failed. The call can fail if the receiving SWF file refuses the connection. If the value of the level property is "status", the call was successful; if the value is "error", the call failed.
client Indicates the object on which callback methods are invoked.ObjectThe client property must be set to a non-null object. TypeErrorTypeError Indicates the object on which callback methods are invoked. The default object is this, the local connection being created. You can set the client property to another object, and callback methods are invoked on that other object. domain A string representing the domain of the location of the current file.String A string representing the domain of the location of the current file.

In content running in the application security sandbox in Adobe AIR (content installed with the AIR application), the runtime uses the string app# followed by the application ID for the AIR application (defined in the application descriptor file) in place of the superdomain. For example a connectionName for an application with the application ID com.example.air.MyApp connectionName resolves to "app#com.example.air.MyApp:connectionName".

In SWF files published for Flash Player 9 or later, the returned string is the exact domain of the file, including subdomains. For example, if the file is located at www.adobe.com, this command returns "www.adobe.com".

If the current file is a local file residing on the client computer running in Flash Player, this command returns "localhost".

The most common ways to use this property are to include the domain name of the sending LocalConnection object as a parameter to the method you plan to invoke in the receiving LocalConnection object, or to use it with LocalConnection.allowDomain() to accept commands from a specified domain. If you are enabling communication only between LocalConnection objects that are located in the same domain, you probably don't need to use this property.

flash.net.LocalConnection.allowDomain()flash.net.LocalConnection.connect()
isSupported The isSupported property is set to true if the LocalConnection class is supported on the current platform, otherwise it is set to false.Boolean The isSupported property is set to true if the LocalConnection class is supported on the current platform, otherwise it is set to false. isPerUserBoolean
NetStream The NetStream class opens a one-way streaming channel over a NetConnection.flash.events:EventDispatcher The NetStream class opens a one-way streaming channel over a NetConnection.

Use the NetStream class to do the following:

  • Call NetStream.play() to play a media file from a local disk, a web server, or Flash Media Server.
  • Call NetStream.publish() to publish a video, audio, and data stream to Flash Media Server.
  • Call NetStream.send() to send data messages to all subscribed clients.
  • Call NetStream.send() to add metadata to a live stream.
  • Call NetStream.appendBytes() to pass ByteArray data into the NetStream.

Note:You cannot play and publish a stream over the same NetStream object.

Adobe AIR and Flash Player 9.0.115.0 and later versions support files derived from the standard MPEG-4 container format. These files include F4V, MP4, M4A, MOV, MP4V, 3GP, and 3G2 if they contain H.264 video, HEAAC v2 encoded audio, or both. H.264 delivers higher quality video at lower bit rates when compared to the same encoding profile in Sorenson or On2. AAC is a standard audio format defined in the MPEG-4 video standard. HE-AAC v2 is an extension of AAC that uses Spectral Band Replication (SBR) and Parametric Stereo (PS) techniques to increase coding efficiency at low bit rates.

For information about supported codecs and file formats, see the following:

  • Flash Media Server documentation
  • Exploring Flash Player support for high-definition H.264 video and AAC audio
  • FLV/F4V open specification documents

Receiving data from a Flash Media Server stream, progressive F4V file, or progressive FLV file

Flash Media Server, F4V files, and FLV files can send event objects containing data at specific data points during streaming or playback. You can handle data from a stream or FLV file during playback in two ways:

  • Associate a client property with an event handler to receive the data object. Use the NetStream.client property to assign an object to call specific data handling functions. The object assigned to the NetStream.client property can listen for the following data points: onCuePoint(), onImageData(), onMetaData(), onPlayStatus(), onSeekPoint(), onTextData(), and onXMPData(). Write procedures within those functions to handle the data object returned from the stream during playback. See the NetStream.client property for more information.
  • Associate a client property with a subclass of the NetStream class, then write an event handler to receive the data object. NetStream is a sealed class, which means that properties or methods cannot be added to a NetStream object at runtime. However, you can create a subclass of NetStream and define your event handler in the subclass. You can also make the subclass dynamic and add the event handler to an instance of the subclass.

Wait to receive a NetGroup.Neighbor.Connect event before you use the object replication, direct routing, or posting APIs.

Note: To send data through an audio file, like an mp3 file, use the Sound class to associate the audio file with a Sound object. Then, use the Sound.id3 property to read metadata from the sound file.

The following example uses a Video object with the NetConnection and NetStream classes to load and play an FLV 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 = "http://www.helpexamples.com/flash/video/cuepoints.flv"; private var connection:NetConnection; private var stream:NetStream; private var video:Video = new Video(); 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(); 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); } }
You can get metadata using a function, instead of creating a custom class. The following suggestion, provided by Bill Sanders, shows how to edit the NetConnectionExample code above to call metadata within a function. In this case, the object mdata is used to set up the width and height of a video instance video: //Place the following in the connectStream() function //in the NetConnectionExample code var metaSniffer:Object=new Object(); stream.client=metaSniffer; //stream is the NetStream instance metaSniffer.onMetaData=getMeta; // Add the following function within the NetConnectionExample class private function getMeta (mdata:Object):void { video.width=mdata.width/2; video.height=mdata.height/2; }
flash.media.Videoflash.net.NetConnectionappendBytes()play()publish()send()onImageDataonMetaDatamediaTypeData Dispatched when playing video content and certain type of messages are processed.flash.events.NetDataEventflash.events.NetDataEvent Dispatched when playing video content and certain type of messages are processed.

A NetDataEvent is dispatched for the following messages:

  • onCuePoint
  • onImageData
  • onMetaData
  • onPlayStatus (for code NetStream.Play.Complete)
  • onTextData
  • onXMPData

Note: This event is not dispatched by content running in Flash Player in the browser on Android or Blackberry Tablet OS or by content running in AIR on iOS.

onSeekPoint Called synchronously from appendBytes() when the append bytes parser encounters a point that it believes is a seekable point (for example, a video key frame). Called synchronously from appendBytes() when the append bytes parser encounters a point that it believes is a seekable point (for example, a video key frame). Use this event to construct a seek point table. The byteCount corresponds to the byteCount at the first byte of the parseable message for that seek point, and is reset to zero as described above. To seek, at the event NetStream.Seek.Notify, find the bytes that start at a seekable point and call appendBytes(bytes). If the bytes argument is a ByteArray consisting of bytes starting at the seekable point, the video plays at that seek point.

Note: Calls to appendBytes() from within this callback are ignored.

The onSeekPoint property is a property of the NetStream.client object. The property is listed in the Events section because it responds to data coming into the appendBytes() method. For more information, see the NetStream class description and the NetStream.client property. You cannot use the addEventListener() method, or any other EventDispatcher methods, to listen for or process onSeekPoint as an event. To use onSeekPoint, define a callback function and attach it to one of the following objects:

  • The object that the client property of a NetStream instance references.
  • An instance of a NetStream subclass. NetStream is a sealed class, which means that properties or methods cannot be added to a NetStream object at runtime. However, you can create a subclass of NetStream and define your event handler in the subclass. You can also make the subclass dynamic and add the event handler function to an instance of the subclass.
client
drmStatus Dispatched when the digital rights management (DRM) encrypted content begins playing (when the user is authenticated and authorized to play the content).flash.events.DRMStatusEvent.DRM_STATUSflash.events.DRMStatusEvent Dispatched when the digital rights management (DRM) encrypted content begins playing (when the user is authenticated and authorized to play the content).

DRMStatusEvent object contains information related to the voucher, such as whether the content is available offline or when the voucher expires and users can no longer view the content.

flash.events.DRMStatusEventflash.net.drm.DRMManager.resetDRMVouchers()setDRMAuthenticationCredentials()
drmError Dispatched when a NetStream object, trying to play a digital rights management (DRM) encrypted file, encounters a DRM-related error.flash.events.DRMErrorEvent.DRM_ERRORflash.events.DRMErrorEvent Dispatched when a NetStream object, trying to play a digital rights management (DRM) encrypted file, encounters a DRM-related error. For example, a DRMErrorEvent object is dispatched when the user authorization fails. This may be because the user has not purchased the rights to view the content or because the content provider does not support the viewing application. flash.events.DRMErrorEventflash.net.drm.DRMManager.resetDRMVouchers()setDRMAuthenticationCredentials()drmAuthenticate Dispatched when a NetStream object tries to play a digital rights management (DRM) encrypted content that requires a user credential for authentication before playing.flash.events.DRMAuthenticateEvent.DRM_AUTHENTICATEflash.events.DRMAuthenticateEvent Dispatched when a NetStream object tries to play a digital rights management (DRM) encrypted content that requires a user credential for authentication before playing.

Use the setDRMAuthenticationCredentials() method of the NetStream object to authenticate the user. If user authentication failed, the application retries authentication and dispatches a new DRMAuthenticateEvent event for the NetStream object.

flash.events.DRMAuthenticateEventflash.net.drm.DRMManager.resetDRMVouchers()setDRMAuthenticationCredentials()
onDRMContentData Establishes a listener to respond when AIR extracts DRM content metadata embedded in a media file. Establishes a listener to respond when AIR extracts DRM content metadata embedded in a media file.

A DRMContentData object contains the information needed to obtain a voucher required to play a DRM-protected media file. Use the DRMManager class to download the voucher with this information.

onDRMContentData is a property of the NetStream.client object. This property is listed in the Events section because it responds to a data event when preloading embedded data from a local media file. For more information, see the NetStream class description. You cannot use the addEventListener() method, or any other EventDispatcher methods, to listen for, or process onDRMContentData as an event. Rather, you must define a single callback function and attach it directly to one of the following objects:

  • The object that the client property of a NetStream instance references.
  • An instance of a NetStream subclass. NetStream is a sealed class, which means that properties or methods cannot be added to a NetStream object at runtime. However, you can create a subclass of NetStream and define your event handler in the subclass or make the subclass dynamic and add the event handler function to an instance of the subclass.
flash.net.drm.DRMContentDatapreloadEmbeddedData()flash.net.drm.DRMManagerflash.net.drm.DRMVoucher
onPlayStatus Establishes a listener to respond when a NetStream object has completely played a stream. Establishes a listener to respond when a NetStream object has completely played a stream. The associated event object provides information in addition to what's returned by the netStatus event. You can use this property to trigger actions in your code when a NetStream object has switched from one stream to another stream in a playlist (as indicated by the information object NetStream.Play.Switch) or when a NetStream object has played to the end (as indicated by the information object NetStream.Play.Complete).

onPlayStaus is actually a property of the NetStream.client object. The property is listed in the Events section because it responds to a data event, either when streaming media using Flash Media Server or during FLV file playback. For more information, see the NetStream class description. You cannot use the addEventListener() method, or any other EventDispatcher methods, to listen for, or process onPlayStatus as an event. Define a callback function and attach it to one of the following objects:

  • The object that the client property of a NetStream instance references.
  • An instance of a NetStream subclass. NetStream is a sealed class, which means that properties or methods cannot be added to a NetStream object at runtime. Create a subclass of NetStream and define your event handler in the subclass. You can also make the subclass dynamic and add the event handler function to an instance of the subclass.

This event can return an information object with the following properties:

Code propertyLevel propertyMeaningNetStream.Play.Switch"status"The subscriber is switching from one stream to another in a playlist.NetStream.Play.Complete"status"Playback has completed.NetStream.Play.TransitionComplete"status"The subscriber is switching to a new stream as a result of stream bit-rate switching
clientflash.events.NetStatusEvent.NET_STATUSasyncErroronMetaDataonCuePoint
onCuePoint Establishes a listener to respond when an embedded cue point is reached while playing a video file. Establishes a listener to respond when an embedded cue point is reached while playing a video file. You can use the listener to trigger actions in your code when the video reaches a specific cue point, which lets you synchronize other actions in your application with video playback events. For information about video file formats supported by Flash Media Server, see the www.adobe.com/go/learn_fms_fileformats_en.

onCuePoint is actually a property of the NetStream.client object. IThe property is listed in the Events section because it responds to a data event, either when streaming media using Flash Media Server or during FLV file playback. For more information, see the NetStream class description. You cannot use the addEventListener() method, or any other EventDispatcher methods, to listen for, or process onCuePoint as an event. Define a callback function and attach it to one of the following objects:

  • The object that the client property of a NetStream instance references.
  • An instance of a NetStream subclass. NetStream is a sealed class, which means that properties or methods cannot be added to a NetStream object at runtime. Create a subclass of NetStream and define your event handler in the subclass. You can also make the subclass dynamic and add the event handler function to an instance of the subclass.

The associated event listener is triggered after a call to the NetStream.play() method, but before the video playhead has advanced.

You can embed the following types of cue points in a video file:

  • A navigation cue point specifies a keyframe within the video file and the cue point's time property corresponds to that exact keyframe. Navigation cue points are often used as bookmarks or entry points to let users navigate through the video file.
  • An event cue point specifies a time. The time may or may not correspond to a specific keyframe. An event cue point usually represents a time in the video when something happens that could be used to trigger other application events.

The onCuePoint event object has the following properties:

PropertyDescriptionnameThe name given to the cue point when it was embedded in the video file.parametersAn associative array of name and value pair strings specified for this cue point. Any valid string can be used for the parameter name or value.timeThe time in seconds at which the cue point occurred in the video file during playback.typeThe type of cue point that was reached, either navigation or event.

You can define cue points in a video file when you first encode the file, or when you import a video clip in the Flash authoring tool by using the Video Import wizard.

The onMetaData event also retrieves information about the cue points in a video file. However the onMetaData event gets information about all of the cue points before the video begins playing. The onCuePoint event receives information about a single cue point at the time specified for that cue point during playback.

Generally, to have your code respond to a specific cue point at the time it occurs, use the onCuePoint event to trigger some action in your code.

You can use the list of cue points provided to the onMetaData event to let the user start playing the video at predefined points along the video stream. Pass the value of the cue point's time property to the NetStream.seek() method to play the video from that cue point.

The following example shows how you can load external FLV files and respond to metadata and cue points. Example provided by ActionScriptExamples.com. var video:Video = new Video(); addChild(video); var nc:NetConnection = new NetConnection(); nc.connect(null); var ns:NetStream = new NetStream(nc); ns.client = {}; ns.client.onMetaData = ns_onMetaData; ns.client.onCuePoint = ns_onCuePoint; ns.play("http://www.helpexamples.com/flash/video/cuepoints.flv"); video.attachNetStream(ns); function ns_onMetaData(item:Object):void { trace("metaData"); // Resize video instance. video.width = item.width; video.height = item.height; // Center video instance on Stage. video.x = (stage.stageWidth - video.width) / 2; video.y = (stage.stageHeight - video.height) / 2; } function ns_onCuePoint(item:Object):void { trace("cuePoint"); trace(item.name + "\t" + item.time); }
clientonMetaData
onTextData Establishes a listener to respond when Flash Player receives text data embedded in a media file that is playing. Establishes a listener to respond when Flash Player receives text data embedded in a media file that is playing. The text data is in UTF-8 format and can contain information about formatting based on the 3GP timed text specification.

onTextData is actually a property of the NetStream.client object. The property is listed in the Events section because it responds to a data event, either when streaming media using Flash Media Server or during FLV file playback. For more information, see the NetStream class description. You cannot use the addEventListener() method, or any other EventDispatcher methods, to listen for, or process onTextData as an event. Define a callback function and attach it to one of the following objects:

  • The object that the client property of a NetStream instance references.
  • An instance of a NetStream subclass. NetStream is a sealed class, which means that properties or methods cannot be added to a NetStream object at runtime. Create a subclass of NetStream and define your event handler in the subclass. You can also make the subclass dynamic and add the event handler function to an instance of the subclass.

The associated event listener is triggered after a call to the NetStream.play() method, but before the video playhead has advanced.

The onTextData event object contains one property for each piece of text data.

The code in this example uses the Netstream.client property to handle the callback functions for onTextData and onImageData. The onImageDataHandler() function uses the onImageData event object imageData to store the byte array. And, the onTextDataHandler() function uses the onTextData event object textData to store the pieces of text data (each piece of data is a property of the textData object).

You need to substitute a real location to a media file with text or image metadata for the location "yourURL" in the code.

You can also handle image and text data using a custom class. See the article Handling metadata and cue points in Flash video for more information and examples.

package { import flash.display.*; import flash.net.*; import flash.media.*; import flash.system.*; import flash.events.*; public class OnTextDataExample extends Sprite { public function OnTextDataExample():void { var customClient:Object = new Object(); customClient.onImageData = onImageDataHandler; customClient.onTextData = onTextDataHandler; var my_nc:NetConnection = new NetConnection(); my_nc.connect(null); var my_ns:NetStream = new NetStream(my_nc); my_ns.play("yourURL"); my_ns.client = customClient; var my_video:Video = new Video(); my_video.attachNetStream(my_ns); addChild(my_video); } public function onImageDataHandler(imageData:Object):void { trace("imageData length: " + imageData.data.length); var imageloader:Loader = new Loader(); imageloader.loadBytes(imageData.data); // imageData.data is a ByteArray object. addChild(imageloader); } public function onTextDataHandler(textData:Object):void { trace("--- textData properties ----"); var key:String; for (key in textData) { trace(key + ": " + textData[key]); } } } }
NetConnectionclientasyncErrorplay()onImageData
onImageData Establishes a listener to respond when Flash Player receives image data as a byte array embedded in a media file that is playing. Establishes a listener to respond when Flash Player receives image data as a byte array embedded in a media file that is playing. The image data can produce either JPEG, PNG, or GIF content. Use the flash.display.Loader.loadBytes() method to load the byte array into a display object.

onImageData is actually a property of the NetStream.client object. The property is listed in the Events section because it responds to a data event, either when streaming media using Flash Media Server or during FLV file playback. For more information, see the NetStream class description. You cannot use the addEventListener() method, or any other EventDispatcher methods, to listen for, or process onImageData as an event. Define a single callback function and attach it to one of the following objects:

  • The object that the client property of a NetStream instance references.
  • An instance of a NetStream subclass. NetStream is a sealed class, which means that properties or methods cannot be added to a NetStream object at runtime. Create a subclass of NetStream and define your event handler in the subclass. You can also make the subclass dynamic and add the event handler function to an instance of the subclass.

The associated event listener is triggered after a call to the NetStream.play() method, but before the video playhead has advanced.

The onImageData event object contains the image data as a byte array sent through an AMF0 data channel.

The code in this example uses the Netstream.client property to handle the callback functions for onTextData and onImageData. The onImageDataHandler() function uses the onImageData event object imageData to store the byte array. And, the onTextDataHandler() function uses the onTextData event object textData to store the pieces of text data (each piece of data is a property of the textData object).

You need to substitute a real location to a media file with text or image metadata for the location "yourURL" in the code.

You can also handle image and text data using a custom class. See the article Handling metadata and cue points in Flash video for more information and examples.

package { import flash.display.*; import flash.net.*; import flash.media.*; import flash.system.*; import flash.events.*; public class OnTextDataExample extends Sprite { public function OnTextDataExample():void { var customClient:Object = new Object(); customClient.onImageData = onImageDataHandler; customClient.onTextData = onTextDataHandler; var my_nc:NetConnection = new NetConnection(); my_nc.connect(null); var my_ns:NetStream = new NetStream(my_nc); my_ns.play("yourURL"); my_ns.client = customClient; var my_video:Video = new Video(); my_video.attachNetStream(my_ns); addChild(my_video); } public function onImageDataHandler(imageData:Object):void { trace("imageData length: " + imageData.data.length); var imageloader:Loader = new Loader(); imageloader.loadBytes(imageData.data); // imageData.data is a ByteArray object. addChild(imageloader); } public function onTextDataHandler(textData:Object):void { trace("--- textData properties ----"); var key:String; for (key in textData) { trace(key + ": " + textData[key]); } } } }
NetConnectionflash.display.Loader.loadBytes()clientasyncErrorplay()onTextData
onMetaData Establishes a listener to respond when Flash Player receives descriptive information embedded in the video being played. Establishes a listener to respond when Flash Player receives descriptive information embedded in the video being played. For information about video file formats supported by Flash Media Server, see the www.adobe.com/go/learn_fms_fileformats_en.

onMetaData is actually a property of the NetStream.client object. The property is listed in the Events section because it responds to a data event, either when streaming media using Flash Media Server or during FLV file playback. For more information, see the NetStream class description and the NetStream.client property. You cannot use the addEventListener() method, or any other EventDispatcher methods, to listen for or process onMetaData as an event. Define a single callback function and attach it to one of the following objects:

  • The object that the client property of a NetStream instance references.
  • An instance of a NetStream subclass. NetStream is a sealed class, which means that properties or methods cannot be added to a NetStream object at runtime. You can create a subclass of NetStream and define your event handler in the subclass. You can also make the subclass dynamic and add the event handler function to an instance of the subclass.

The Flash Video Exporter utility (version 1.1 or later) embeds a video's duration, creation date, data rates, and other information into the video file itself. Different video encoders embed different sets of meta data.

The associated event listener is triggered after a call to the NetStream.play() method, but before the video playhead has advanced.

In many cases, the duration value embedded in stream metadata approximates the actual duration but is not exact. In other words, it does not always match the value of the NetStream.time property when the playhead is at the end of the video stream.

The event object passed to the onMetaData event handler contains one property for each piece of data.

The following example shows how you can load external FLV files and respond to metadata and cue points. Example provided by ActionScriptExamples.com. var video:Video = new Video(); addChild(video); var nc:NetConnection = new NetConnection(); nc.connect(null); var ns:NetStream = new NetStream(nc); ns.client = {}; ns.client.onMetaData = ns_onMetaData; ns.client.onCuePoint = ns_onCuePoint; ns.play("http://www.helpexamples.com/flash/video/cuepoints.flv"); video.attachNetStream(ns); function ns_onMetaData(item:Object):void { trace("metaData"); // Resize video instance. video.width = item.width; video.height = item.height; // Center video instance on Stage. video.x = (stage.stageWidth - video.width) / 2; video.y = (stage.stageHeight - video.height) / 2; } function ns_onCuePoint(item:Object):void { trace("cuePoint"); trace(item.name + "\t" + item.time); }
NetConnectionclientasyncErroronCuePointplay()time
onXMPData Establishes a listener to respond when Flash Player receives information specific to Adobe Extensible Metadata Platform (XMP) embedded in the video being played. Establishes a listener to respond when Flash Player receives information specific to Adobe Extensible Metadata Platform (XMP) embedded in the video being played. For information about video file formats supported by Flash Media Server, see the www.adobe.com/go/learn_fms_fileformats_en.

onXMPData is actually a property of the NetStream.client object. The property is listed in the Events section because it responds to a data event, either when streaming media using Flash Media Server or during FLV file playback. For more information, see the NetStream class description and the NetStream.client property. You cannot use the addEventListener() method, or any other EventDispatcher methods, to listen for or process onMetaData as an event. Define a callback function and attach it to one of the following objects:

  • The object that the client property of a NetStream instance references.
  • An instance of a NetStream subclass. NetStream is a sealed class, which means that properties or methods cannot be added to a NetStream object at runtime. However, you can create a subclass of NetStream and define your event handler in the subclass. You can also make the subclass dynamic and add the event handler function to an instance of the subclass.

The associated event listener is triggered after a call to the NetStream.play() method, but before the video playhead has advanced.

The object passed to the onXMPData() event handling function has one data property, which is a string. The string is generated from a top-level UUID box. (The 128-bit UUID of the top level box is BE7ACFCB-97A9-42E8-9C71-999491E3AFAC.) This top-level UUID box contains exactly one XML document represented as a null-terminated UTF-8 string.

flash.net.NetConnectionclientasyncErroronCuePointplay()time
netStatus Dispatched when a NetStream object is reporting its status or error condition.flash.events.NetStatusEvent.NET_STATUSflash.events.NetStatusEvent Dispatched when a NetStream 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 if a connection attempt succeeded or failed. flash.events.NetStatusEvent.infoioError Dispatched when an input or output error occurs that causes a network operation to fail.flash.events.IOErrorEvent.IO_ERRORflash.events.IOErrorEvent Dispatched when an input or output error occurs that causes a network operation to fail. asyncError Dispatched when an exception is thrown asynchronously &#x2014; that is, from native asynchronous code.flash.events.AsyncErrorEvent.ASYNC_ERRORflash.events.AsyncErrorEvent Dispatched when an exception is thrown asynchronously — that is, from native asynchronous code. This event is dispatched when a server calls a method on the client that is not defined. onPlayStatusonMetaDatastatus Dispatched when the application attempts to play content encrypted with digital rights management (DRM), by invoking the NetStream.play() method.flash.events.StatusEvent.STATUSflash.events.StatusEvent Dispatched when the application attempts to play content encrypted with digital rights management (DRM), by invoking the NetStream.play() method. The value of the status code property will be "DRM.encryptedFLV". play()NetStream Creates a stream that you can use to play media files and send data over a NetConnection object.The NetConnection instance is not connected. ArgumentErrorArgumentErrorconnectionflash.net:NetConnectionA NetConnection object. peerIDStringconnectToFMSThis optional parameter is available in Flash Player 10 and later, for use with RTMFP connections. (If the value of the NetConnection.protocol property is not "rtmfp", this parameter is ignored.) Use one of the following values:
  • To connect to Flash Media Server, specify NetStream.CONNECT_TO_FMS.
  • To publish directly to peers, specify NetStream.DIRECT_CONNECTIONS.
  • To play directly from a specific peer, specify that peer's identity (see NetConnection.nearID and NetStream.farID).
  • (Flash Player 10.1 or AIR 2 or later) To publish or play a stream in a peer-to-peer multicast group, specify a groupspec string (see the GroupSpecifier class).

In most cases, a groupspec has the potential to use the network uplink on the local system. In this case, the user is asked for permission to use the computer's network resources. If the user allows this use, a NetStream.Connect.Success NetStatusEvent is sent to the NetConnection's event listener. If the user denies permission, a NetStream.Connect.Rejected event is sent. When specifying a groupspec, until a NetStream.Connect.Success event is received, it is an error to use any method of the NetStream object, and an exception is raised.

If you include this parameter in your constructor statement but pass a value of null, the value is set to "connectToFMS".

Creates a stream that you can use to play media files and send data over a NetConnection object. The following code shows a connection to download and display, progressively, a video assigned to the variable videoURL: var my_nc:NetConnection = new NetConnection(); my_nc.connect(null); var my_ns:NetStream = new NetStream(my_nc); my_ns.play(videoURL); var my_video:Video = new Video(); my_video.attachNetStream(my_ns); addChild(my_video); The following code shows a connection to stream and display a video (assigned to the variable videoURL) on a remote Flash Media Server instance specified in the connect() command: var my_nc:NetConnection = new NetConnection(); my_nc.connect("rtmp://www.yourfmsserver.com/someappname"); var my_ns:NetStream = new NetStream(my_nc, NetStream.CONNECT_TO_FMS); my_ns.play(videoURL); var my_video:Video = new Video(); my_video.attachNetStream(my_ns); addChild(my_video);
CONNECT_TO_FMSDIRECT_CONNECTIONSfarIDflash.media.Video.attachCamera()flash.net.GroupSpecifierflash.net.GroupSpecifier.groupspecWithAuthorizations()flash.net.GroupSpecifier.groupspecWithoutAuthorizations()flash.net.GroupSpecifier.multicastEnabledflash.net.NetConnectionflash.net.NetConnection.nearIDflash.net.NetConnection.protocolflash.net.NetGroupflash.events.NetStatusEvent.info.code="NetStream.Connect.Rejected"flash.events.NetStatusEvent.info.code="NetStream.Connect.Success"
appendBytesAction Indicates a timescale discontinuity, flushes the FIFO, and tells the byte parser to expect a file header or the beginning of an FLV tag.netStreamAppendBytesActionString Indicates a timescale discontinuity, flushes the FIFO, and tells the byte parser to expect a file header or the beginning of an FLV tag.

Calls to NetStream.seek() flush the NetStream buffers. The byte parser remains in flushing mode until you call appendBytesAction() and pass the RESET_BEGIN or RESET_SEEK argument. Capture the "NetStream.Seek.Notify" event to call appendBytesAction() after a seek. A new file header can support playlists and seeking without calling NetStream.seek().

You can also call this method to reset the byte counter for the onSeekPoint()) callback.

appendBytes()seek()flash.net.NetStreamAppendBytesAction
appendBytes Passes a ByteArray into a NetStream for playout.bytesflash.utils:ByteArray Passes a ByteArray into a NetStream for playout. Call this method on a NetStream in "Data Generation Mode". To put a NetStream into Data Generation Mode, call NetStream.play(null) on a NetStream created on a NetConnection connected to null. Calling appendBytes() on a NetStream that isn't in Data Generation Mode is an error and raises an exception.

The byte parser understands an FLV file with a header. After the header is parsed, appendBytes() expects all future calls to be continuations of the same real or virtual file. Another header is not expected unless appendBytesAction(NetStreamAppendBytesAction.RESET_BEGIN) is called.

A NetStream object has two buffers: the FIFO from appendBytes() to the NetStream, and the playout buffer. The FIFO is the partial-FLV-tag reassembly buffer and contains no more than one incomplete FLV tag. Calls to NetStream.seek() flush both buffers. After a call to seek(), call appendBytesAction() to reset the timescale to begin at the timestamp of the next appended message.

Each call to appendBytes() adds bytes into the FIFO until an FLV tag is complete. When an FLV tag is complete, it moves to the playout buffer. A call to appendBytes() can write multiple FLV tags. The first bytes complete an existing FLV tag (which moves to the playout buffer). Complete FLV tags move to the playout buffer. Remaining bytes that don’t form a complete FLV tag go into the FIFO. Bytes in the FIFO are either completed by a call to appendBytes() or flushed by a call to appendBytesAction() with the RESET_SEEK or RESET_BEGIN argument.

Note: The byte parser may not be able to completely decode a call to appendBytes() until a subsequent call to appendBytes() is made.

appendBytesAction()seek()
attachAudio Attaches an audio stream to a NetStream object from a Microphone object passed as the source."null" microphoneflash.media:MicrophoneThe source of the audio stream to be transmitted. Attaches an audio stream to a NetStream object from a Microphone object passed as the source. This method is available only to the publisher of the specified stream.

Use this method with Flash Media Server to send live audio to the server. Call this method before or after you call the publish() method.

Set the Microphone.rate property to match the rate of the sound capture device. Call setSilenceLevel() to set the silence level threshold. To control the sound properties (volume and panning) of the audio stream, use the Microphone.soundTransform property.

     var nc:NetConnection = new NetConnection();
     nc.connect("rtmp://server.domain.com/app");
     var ns:NetStream = new NetStream(nc);
     
     var live_mic:Microphone = Microphone.get();
     live_mic.rate = 8;
     live_mic.setSilenceLevel(20,200);
     
     var soundTrans:SoundTransform = new SoundTransform();
     soundTrans.volume = 6;
     live_mic.soundTransform = soundTrans;
     
     ns.attachAudio(live_mic);
     ns.publish("mic_stream","live")
     

To hear the audio, call the NetStream.play() method and call DisplayObjectContainer.addChild() to route the audio to an object on the display list.

play()flash.media.Microphoneflash.display.DisplayObjectContainer.addChild()
attachCamera Starts capturing video from a camera, or stops capturing if theCamera is set to null.theCameraflash.media:CameraThe source of the video transmission. Valid values are a Camera object (which starts capturing video) and null. If you pass null, the application stops capturing video, and any additional parameters you send are ignored. snapshotMillisecondsint-1Specifies whether the video stream is continuous, a single frame, or a series of single frames used to create time-lapse photography.
  • If you omit this parameter, the application captures all video until you pass a value of null to attachCamera.
  • If you pass 0, the application captures only a single video frame. Use this value to transmit "snapshots" within a preexisting stream. Flash Player or AIR interprets invalid, negative, or nonnumeric arguments as 0.
  • If you pass a positive number, the application captures a single video frame and then appends a pause of the specified length as a trailer on the snapshot. Use this value to create time-lapse photography effects.
Starts capturing video from a camera, or stops capturing if theCamera is set to null. This method is available only to the publisher of the specified stream.

This method is intended for use with Flash Media Server; for more information, see the class description.

After attaching the video source, you must call NetStream.publish() to begin transmitting. Subscribers who want to display the video must call the NetStream.play() and Video.attachCamera() methods to display the video on the stage.

You can use snapshotMilliseconds to send a single snapshot (by providing a value of 0) or a series of snapshots — in effect, time-lapse footage — by providing a positive number that adds a trailer of the specified number of milliseconds to the video feed. The trailer extends the display time of the video message. By repeatedly calling attachCamera() with a positive value for snapshotMilliseconds, the sequence of alternating snapshots and trailers creates time-lapse footage. For example, you could capture one frame per day and append it to a video file. When a subscriber plays the file, each frame remains onscreen for the specified number of milliseconds and then the next frame is displayed.

The purpose of the snapshotMilliseconds parameter is different from the fps parameter you can set with Camera.setMode(). When you specify snapshotMilliseconds, you control how much time elapses between recorded frames. When you specify fps using Camera.setMode(), you are controlling how much time elapses during recording and playback.

For example, suppose you want to take a snapshot every 5 minutes for a total of 100 snapshots. You can do this in two ways:

  • You can issue a NetStream.attachCamera(myCamera, 500) command 100 times, once every 5 minutes. This takes 500 minutes to record, but the resulting file will play back in 50 seconds (100 frames with 500 milliseconds between frames).
  • You can issue a Camera.setMode() command with an fps value of 1/300 (one per 300 seconds, or one every 5 minutes), and then issue a NetStream.attachCamera(source) command, letting the camera capture continuously for 500 minutes. The resulting file will play back in 500 minutes — the same length of time that it took to record — with each frame being displayed for 5 minutes.

Both techniques capture the same 500 frames, and both approaches are useful; the approach to use depends primarily on your playback requirements. For example, in the second case, you could be recording audio the entire time. Also, both files would be approximately the same size.

attach Attaches a stream to a new NetConnection object.connectionflash.net:NetConnection Attaches a stream to a new NetConnection object. Call this method to attach a NetStream to a new NetConnection object after a connection has dropped and been reconnected. Flash Player and AIR resume streaming from the playback point when the connection was lost.You can also use this method to implement load balancing.

This method requires Flash Media Server version 3.5.3 or later.

To use this method to implement stream reconnection, see the Flash Media Server 3.5.3 documentation.

To use this method to implement load balancing, do the following:

  1. Attach a connected stream to a NetConnection object on another server.
  2. After the stream is successfully attached to the new connection, call NetConnection.close() on the prior connection to prevent data leaks.
  3. Call NetStream.play2() and set the value of NetStreamPlayOptions.transition to RESUME. Set the rest of the NetStreamPlayOptions properties to the same values you used when you originally called NetStream.play() or NetStream.play2() to start the stream.
play2()NetStreamPlayOptions.transition
close Stops playing all data on the stream, sets the time property to 0, and makes the stream available for another use. Stops playing all data on the stream, sets the time property to 0, and makes the stream available for another use. This method also deletes the local copy of a video file that was downloaded through HTTP. Although the application deletes the local copy of the file that it creates, a copy might persist in the cache directory. If you must completely prevent caching or local storage of the video file, use Flash Media Server.

When using Flash Media Server, this method is invoked implicitly when you call NetStream.play() from a publishing stream or NetStream.publish() from a subscribing stream. Please note that:

  • If close() is called from a publishing stream, the stream stops publishing and the publisher can now use the stream for another purpose. Subscribers no longer receive anything that was being published on the stream, because the stream has stopped publishing.
  • If close() is called from a subscribing stream, the stream stops playing for the subscriber, and the subscriber can use the stream for another purpose. Other subscribers are not affected.
  • You can stop a subscribing stream from playing, without closing the stream or changing the stream type by using flash.net.NetStream.play(false).
pause()play()publish()
onPeerConnect Invoked when a peer-publishing stream matches a peer-subscribing stream.Booleansubscriberflash.net:NetStream Invoked when a peer-publishing stream matches a peer-subscribing stream. Before the subscriber is connected to the publisher, call this method to allow the ActionScript code fine access control for peer-to-peer publishing. The following code shows an example of how to create a callback function for this method: var c:Object = new Object; c.onPeerConnect = function(subscriber:NetStream):Boolean { if (accept) return true; else return false; }; m_netStream.client = c;

If a peer-publisher does not implement this method, all peers are allowed to play any published content.

pause Pauses playback of a video stream. Pauses playback of a video stream. Calling this method does nothing if the video is already paused. To resume play after pausing a video, call resume(). To toggle between pause and play (first pausing the video, then resuming), call togglePause().

Starting with Flash Player 9.0.115.0, Flash Player no longer clears the buffer when NetStream.pause() is called. This behavior is called "smart pause". Before Flash Player 9.0.115.0, Flash Player waited for the buffer to fill up before resuming playback, which often caused a delay.

Note: For backwards compatibility, the "NetStream.Buffer.Flush" event (see the NetStatusEvent.info property) still fires, although the server does not flush the buffer.

For a single pause, the NetStream.bufferLength property has a limit of either 60 seconds or twice the value of NetStream.bufferTime, whichever value is higher. For example, if bufferTime is 20 seconds, Flash Player buffers until NetStream.bufferLength is the higher value of either 20~~2 (40), or 60, so in this case it buffers until bufferLength is 60. If bufferTime is 40 seconds, Flash Player buffers until bufferLength is the higher value of 40~~2 (80), or 60, so in this case it buffers until bufferLength is 80 seconds.

The bufferLength property also has an absolute limit. If any call to pause() causes bufferLength to increase more than 600 seconds or the value of bufferTime ~~ 2, whichever is higher, Flash Player flushes the buffer and resets bufferLength to 0. For example, if bufferTime is 120 seconds, Flash Player flushes the buffer if bufferLength reaches 600 seconds; if bufferTime is 360 seconds, Flash Player flushes the buffer if bufferLength reaches 720 seconds.

Tip: You can use NetStream.pause() in code to buffer data while viewers are watching a commercial, for example, and then unpause when the main video starts.

close()play()resume()togglePause()bufferLengthbufferTimeflash.events.NetStatusEvent.info
play2 Switches seamlessly between files with multiple bit rates and allows a NetStream to resume when a connection is dropped and reconnected.paramflash.net:NetStreamPlayOptions Switches seamlessly between files with multiple bit rates and allows a NetStream to resume when a connection is dropped and reconnected.

This method is an enhanced version of NetStream.play(). Like the play() method, the play2() method begins playback of a media file or queues up media files to create a playlist. When used with Flash Media Server, it can also request that the server switch to a different media file. The transition occurs seamlessly in the client application. The following features use play2() stream switching:

Dynamic streaming

Dynamic streaming (supported in Flash Media Server 3.5 and later) lets you serve a stream encoded at multiple bit rates. As a viewer's network conditions change, they receive the bitrate that provides the best viewing experience. Use the NetStreamInfo class to monitor network conditions and switch streams based on the data. You can also switch streams for clients with different capabilities. For more information, see "Dynamic streaming" in the "Adobe Flash Media Server Developer Guide".

Adobe built a custom ActionScript class called DynamicStream that extends the NetStream class. You can use the DynamicStream class to implement dynamic streaming in an application instead of writing your own code to detect network conditions. Even if you choose to write your own dynamic streaming code, use the DynamicStream class as a reference implementation. Download the class and the class documentation at the Flash Media Server tools and downloads page.

Stream reconnecting

Stream reconnecting (supported in Flash Media Server 3.5.3 and later) lets users to experience media uninterrupted even when they lose their connection. The media uses the buffer to play while your ActionScript logic reconnects to Flash Media Server. After reconnection, call NetStream.attach() to use the same NetStream object with the new NetConnection. Use the NetStream.attach(), NetStreamPlayTransitions.RESUME, and NetStreamPlayTrasitions.APPEND_AND_WAIT APIs to reconnect a stream. For more information, see the Flash Media Server 3.5.3 documentation.

play()attach()NetStreamPlayOptionsNetStreamPlayTransitions
play Plays a media file from a local directory or a web server; plays a media file or a live stream from Flash Media Server.Local untrusted SWF files cannot communicate with the Internet. You can work around this restriction by reclassifying this SWF file as local-with-networking or trusted. SecurityErrorSecurityErrorAt least one parameter must be specified. ArgumentErrorArgumentErrorThe NetStream Object is invalid. This may be due to a failed NetConnection. ErrorErrorarguments

Play a local file

The location of a media file. Argument can be a String, a URLRequest.url property, or a variable referencing either. In Flash Player and in AIR content outside the application security sandbox, you can play local video files that are stored in the same directory as the SWF file or in a subdirectory; however, you can't navigate to a higher-level directory.

With AIR content in the application security sandbox, the path you specify for the media file is relative to the SWF file's directory. However, you cannot navigate above the SWF file's directory. Do not specify a full path since AIR treats it as a relative path.

Play a file from Flash Media Server

NameRequiredDescriptionname:ObjectRequired The name of a recorded file, an identifier for live data published by NetStream.publish(), or false. If false, the stream stops playing and any additional parameters are ignored. For more information on the filename syntax, see the file format table following this table.start:NumberOptional The start time, in seconds. Allowed values are -2, -1, 0, or a positive number. The default value is -2, which looks for a live stream, then a recorded stream, and if it finds neither, opens a live stream. If -1, plays only a live stream. If 0 or a positive number, plays a recorded stream, beginning start seconds in. len:Number Optional if start is specified. The duration of the playback, in seconds. Allowed values are -1, 0, or a positive number. The default value is -1, which plays a live or recorded stream until it ends. If 0, plays a single frame that is start seconds from the beginning of a recorded stream. If a positive number, plays a live or recorded stream for len seconds. reset:Object Optional if len is specified. Whether to clear a playlist. The default value is 1 or true, which clears any previous play calls and plays name immediately. If 0 or false, adds the stream to a playlist. If 2, maintains the playlist and returns all stream messages at once, rather than at intervals. If 3, clears the playlist and returns all stream messages at once.

You can play back the file formats described in the following table. The syntax differs depending on the file format.

File formatSyntaxExampleFLVSpecify the stream name (in the "samples" directory) as a string without a filename extension.ns.play("samples/myflvstream");mp3 or ID3Specify the stream name (in the "samples" directory) as a string with the prefix mp3: or id3: without a filename extension.

ns.play("mp3:samples/mymp3stream");

ns.play("id3:samples/myid3data");

MPEG-4-based files (such as F4V and MP4)Specify the stream name (in the "samples" directory) as a string with the prefix mp4: The prefix indicates to the server that the file contains H.264-encoded video and AAC-encoded audio within the MPEG-4 Part 14 container format. If the file on the server has a file extension, specify it.

ns.play("mp4:samples/myvideo.f4v");

ns.play("mp4:samples/myvideo.mp4");

ns.play("mp4:samples/myvideo");

ns.play("mp4:samples/myvideo.mov");

RAWSpecify the stream name (in the "samples" directory) as a string with the prefix raw:ns.play("raw:samples/myvideo");

Enable Data Generation Mode

To enable "Data Generation Mode", pass the value null to a NetStream created on a NetConnection connected to null. In this mode, call appendBytes() to deliver data to the NetStream. (Passing null also resets the byte counter for the onSeekPoint() callback.)

Plays a media file from a local directory or a web server; plays a media file or a live stream from Flash Media Server. Dispatches a NetStatusEvent object to report status and error messages.

For information about supported codecs and file formats, see the following:

  • Flash Media Server documentation
  • Exploring Flash Player support for high-definition H.264 video and AAC audio
  • FLV/F4V open specification documents

Workflow for playing a file or live stream

  1. Create a NetConnection object and call NetConnection.connect().

    To play a file from a local directory or web server, pass null.

    To play a recorded file or live stream from Flash Media Server, pass the URI of a Flash Media Server application.

  2. Call NetConnection.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler) to listen for NetStatusEvent events.
  3. On "NetConnection.Connect.Success", create a NetStream object and pass the NetConnection object to the constructor.
  4. Create a Video object and call Video.attachNetStream() and pass the NetStream object.
  5. Call NetStream.play().

    To play a live stream, pass the stream name passed to the NetStream.publish() method.

    To play a recorded file, pass the file name.

  6. Call addChild() and pass the Video object to display the video.

Note:To see sample code, scroll to the example at the bottom of this page.

Enable Data Generation Mode

Call play(null) to enable "Data Generation Mode". In this mode, call the appendBytes() method to deliver data to the NetStream. Use Data Generation Mode to stream content over HTTP from the Adobe HTTP Dynamic Streaming Origin Module on an Apache HTTP Server. HTTP Dynamic Streaming lets clients seek quickly to any point in a file. The Open Source Media Framework (OSMF) supports HTTP Dynamic Streaming for vod and live streams. For examples of how to use NetStream Data Generation Mode, download the OSMF source. For more information about HTTP Dynamic Streaming, see HTTP Dynamic Streaming.

When you use this method without Flash Media Server, there are security considerations. A file in the local-trusted or local-with-networking sandbox can load and play a video file from the remote sandbox, but cannot access the remote file's data without explicit permission in the form of a URL policy file. Also, you can prevent a SWF file running in Flash Player from using this method by setting the allowNetworking parameter of the the object and embed tags in the HTML page that contains the SWF content. For more information related to security, see the Flash Player Developer Center Topic: Security.

Flash Media Server This example plays a recorded F4V file from the "samples" directory, starting at the beginning, for up to 100 seconds. With MPEG-4 files, if the file on the server has a filename extension the play() method must specify a filename extension. ns.play("mp4:samples/record1.f4v", 0, 100, true); Flash Media Server This example plays a live FLV stream published by a client, from beginning to end, starting immediately: ns.play("livestream"); The following example shows how to load an external FLV file: var MyVideo:Video = new Video(); addChild(MyVideo); var MyNC:NetConnection = new NetConnection(); MyNC.connect(null); var MyNS:NetStream = new NetStream(MyNC); MyNS.play("http://www.helpexamples.com/flash/video/clouds.flv"); MyVideo.attachNetStream(MyNS); //the clouds.flv video has metadata we're not using, so create //an error handler to ignore the message generated by the runtime //about the metadata MyNS.addEventListener(AsyncErrorEvent.ASYNC_ERROR, asyncErrorHandler); function asyncErrorHandler(event:AsyncErrorEvent):void { //ignore metadata error message }
DisplayObjectContainer.addChild()checkPolicyFileappendBytes()statusflash.events:StatusEventDispatched when attempting to play content encrypted with digital rights management (DRM). The value of the code property is "DRM.encryptedFLV". Dispatched when attempting to play content encrypted with digital rights management (DRM).
preloadEmbeddedData Extracts any DRM metadata from a locally stored media file.paramflash.net:NetStreamPlayOptionsA NetStreamPlayOptions describing the options to use while processing the content file. Extracts any DRM metadata from a locally stored media file.

Use preloadEmbeddedMetaData() as the first step in downloading and caching the DRM vouchers needed for offline playback. When embedded DRM metadata is detected in a media file, a DRMContentData object is passed to the NetStream client onDRMContentData function. This DRMContentData object contains the information needed to obtain the voucher required to play the content. Pass the DRMContentDataObject to the DRMManager loadVoucher() method to download the voucher.

The steps for preloading a DRM voucher include:

  • Create a new NetStream object for preloading the metadata.

  • Assign a callback function to the onDRMContentData property of the NetStream client.
  • Create a new NetStreamPlayOptions object and set its streamName property to the the URL string of the local video file.
  • Call preloadEmbeddedMetadata(), passing in the NetStreamPlayOptions object.
  • In response to the onDRMContentData callback, call the DRMManager loadVoucher() method, passing in the DRMContentData object. If the authenticationMethod property of the DRMContentData object has the value, userNameAndPassWord, authenticate the user on the media rights server before loading the voucher.
  • Close the NetStream used for preloading.

Note: To use the same NetStream object to both preload metadata and play content, wait for the onPlayStatus call generated by the preload operation before starting playback.

Downloaded vouchers are stored in a local cache. Playing content online also downloads and caches vouchers. When a DRM-protected content file is viewed, a cached voucher is retrieved from the local store automatically. Use the DRMManager to manage the voucher cache.

Notes: Preloading DRM metadata through HTTP, HTTPS, or RTMP connections is not supported. You can only preload metadata from files stored on the file system.

onDRMContentDataflash.net.drm.DRMContentDataflash.net.drm.DRMManager.loadVoucher()flash.net.drm.DRMVoucherclient
publish Sends streaming audio, video, and data messages from a client to Flash Media Server, optionally recording the stream during transmission.nameStringnullA string that identifies the stream. Clients that subscribe to this stream pass this name when they call NetStream.play(). Don't follow the stream name with a "/". For example, don't use the stream name "bolero/".

You can record files in the formats described in the following table (you cannot use publish() for MP3 format files). The syntax differs depending on the file format.

File formatSyntaxExampleFLVSpecify the stream name as a string without a filename extension.ns.publish("myflvstream");MPEG-4-based files (such as F4V or MP4)Specify the stream name as a string with the prefix mp4: with or without the filename extension. Flash Player doesn't encode using H.264, but Flash Media Server can record any codec in the F4V container. Flash Media Live Encoder can encode using H.264. ns.publish("mp4:myvideo.f4v") ns.publish("mp4:myvideo");RAWSpecify the stream name as a string with the prefix raw:ns.publish("raw:myvideo");

typeStringnullA string that specifies how to publish the stream. Valid values are "record", "append", "appendWithGap", and "live". The default value is "live".
  • If you pass "record", the server publishes and records live data, saving the recorded data to a new file with a name matching the value passed to the name parameter. If the file exists, it is overwritten.
  • If you pass "append", the server publishes and records live data, appending the recorded data to a file with a name that matches the value passed to the name parameter. If no file matching the name parameter is found, it is created.
  • If you pass "appendWithGap", additional information about time coordination is passed to help the server determine the correct transition point when dynamic streaming.
  • If you omit this parameter or pass "live", the server publishes live data without recording it. If a file with a name that matches the value passed to the name parameter exists, it is deleted.
Sends streaming audio, video, and data messages from a client to Flash Media Server, optionally recording the stream during transmission. This method dispatches a NetStatusEvent object with information about the stream. Before you call NetStream.publish(), capture the "NetConnection.Connect.Success" event to verify that the application has successfully connected to Flash Media Server.

While publishing, you can record files in FLV or F4V format. If you record a file in F4V format, use a flattener tool to edit or play the file in another application. To download the tool, see www.adobe.com/go/fms_tools.

Note:Do not use this method to play a stream. To play a stream, call the NetStream.play() method.

Workflow for publishing a stream

  1. Create a NetConnection object and call NetConnection.connect().
  2. Call NetConnection.addEventListener() to listen for NetStatusEvent events.
  3. On the "NetConnection.Connect.Success" event, create a NetStream object and pass the NetConnection object to the constructor.
  4. To capture audio and video, call the NetStream.attachAudio()method and the NetStream.attachCamera() method.
  5. To publish a stream, call the NetStream.publish() method. You can record the data as you publish it so that users can play it back later.

Note: A NetStream can either publish a stream or play a stream, it cannot do both. To publish a stream and view the playback from the server, create two NetStream objects. You can send multiple NetStream objects over one NetConnection object.

When Flash Media Server records a stream it creates a file. By default, the server creates a directory with the application instance name passed to NetConnection.connect() and stores the file in the directory. For example, the following code connects to the default instance of the "lectureseries" application and records a stream called "lecture". The file "lecture.flv" is recorded in the applications/lectureseries/streams/_definst_ directory:

var nc:NetConnection = new NetConnection(); nc.connect("rtmp://fms.example.com/lectureseries"); nc.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler); function netStatusHandler(event:NetStatusEvent):void{ if (event.info.code == "NetConnection.Connect.Success"){ var ns:NetStream = new NetStream(nc); ns.publish("lecture", "record"); } }

The following example connects to the "monday" instance of the same application. The file "lecture.flv" is recorded in the directory /applications/lectureseries/streams/monday:

var nc:NetConnection = new NetConnection(); nc.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler); nc.connect("rtmp://fms.example.com/lectureseries/monday"); function netStatusHandler(event:NetStatusEvent):void{ if (event.info.code == "NetConnection.Connect.Success"){ var ns:NetStream = new NetStream(nc); ns.publish("lecture", "record"); } }
The following example captures video from a camera and publishes it over a NetStream to Flash Media Server. The example displays the video as it's played back from Flash Media Server.

To run this example, you need a camera attached to your computer. You also need to add a Button component and a Label component to the Library.

The application has a button that publishes a stream (sends it to Flash Media Server) only after the application has successfully connected to the server. The application plays back the stream from the server only after the stream has been successfully published. The NetStatusEvent returns an info object with a code property that specifies these cases. The netStatusHandler function handles these events for the NetConnection and NetStream classes.

package { import flash.display.Sprite; import flash.events.*; import flash.media.Video; import flash.media.Camera; import flash.net.NetConnection; import flash.net.NetStream; import fl.controls.Button; import fl.controls.Label; public class NetStream_publish extends Sprite { private var connectionURL:String = "rtmp://localhost/live/"; private var videoURL:String = "liveVideo"; private var nc:NetConnection; private var ns_publish:NetStream; private var ns_playback:NetStream; private var video_publish:Video; private var video_playback:Video; private var cam:Camera; private var b:Button; private var l:Label; public function NetStream_publish() { setUpUI(); nc = new NetConnection(); nc.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler); // Add bandwidth detection handlers on the NetConnection Client to // prevent Reference Errors at runtime when using the "live" and "vod" applications. var clientObj:Object = new Object(); clientObj.onBWDone = onBWDone; clientObj.onBWCheck = onBWCheck; nc.client = clientObj; // Connect to the "live" application on Flash Media Server. nc.connect(connectionURL); } private function netStatusHandler(event:NetStatusEvent):void { trace(event.info.code + " | " + event.info.description); switch (event.info.code) { case "NetConnection.Connect.Success": // Enable the "Publish" button after the client connects to the server. b.enabled = true; break; case "NetStream.Publish.Start": playbackVideo(); break; } } private function publishVideo(event:MouseEvent):void{ // Disable the button so that you can only publish once. b.enabled = false; // Create a NetStream to send video to FMS. ns_publish = new NetStream(nc); ns_publish.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler); // Publish (send) the video to FMS. cam = Camera.getCamera(); ns_publish.attachCamera(cam); ns_publish.publish(videoURL); } private function playbackVideo():void { // Create a NetStream to receive the video from FMS. ns_playback = new NetStream(nc); ns_playback.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler); ns_playback.play(videoURL); // Display the video that was published to FMS. video_playback = new Video(cam.width, cam.height); video_playback.x = cam.width + 20; video_playback.y = 10; video_playback.attachNetStream(ns_playback); addChild(video_playback); } private function setUpUI():void { b = new Button(); b.addEventListener(MouseEvent.CLICK, publishVideo); b.width = 150; b.label = "Publish video to server"; b.move(10, 150); b.enabled = false; l = new Label(); l.width = 150; l.text = "Playing back from server" l.move(190, 150); addChild(b); addChild(l); } // Handlers called by the Flash Media Server "live" and "vod" applications. public function onBWDone(... rest):Boolean { return true; } public function onBWCheck(... rest):Number { return 0; } } }
flash.net.NetConnection.connect()flash.events.NetStatusEvent.info
receiveAudio Specifies whether incoming audio plays on the stream.flagBooleanSpecifies whether incoming audio plays on the stream (true) or not (false). The default value is true. If the specified stream contains only audio data, NetStream.time stops incrementing when you pass false. Specifies whether incoming audio plays on the stream. This method is available only to clients subscribed to the specified stream. It is not available to the publisher of the stream. Call this method before or after you call the NetStream.play() method. For example, attach this method to a button to allow users to mute and unmute the audio. Use this method only on unicast streams that are played back from Flash Media Server. This method doesn't work on RTMFP multicast streams or when using the NetStream.appendBytes() method. receiveVideoFPS Specifies the frame rate for incoming video.FPSNumberSpecifies the frame rate per second at which the incoming video plays. Specifies the frame rate for incoming video. This method is available only to clients subscribed to the specified stream. It is not available to the publisher of the stream. Call this method before or after you call the NetStream.play() method. For example, call this method to allow users to set the video frame rate. To determine the current frame rate, use NetStream.currentFPS. To stop receiving video, pass 0.

When you pass a value to the FPS parameter to limit the frame rate of the video, Flash Media Server attempts to reduce the frame rate while preserving the integrity of the video. Between every two keyframes, the server sends the minimum number of frames needed to satisfy the desired rate. Please note that I-frames (or intermediate frames) must be sent contiguously, otherwise the video is corrupted. Therefore, the desired number of frames is sent immediately and contiguously following a keyframe. Since the frames are not evenly distributed, the motion appears smooth in segments punctuated by stalls.

Use this method only on unicast streams that are played back from Flash Media Server. This method doesn't work on RTMFP multicast streams or when using the NetStream.appendBytes() method.

receiveVideo Specifies whether incoming video plays on the stream.flagBooleanSpecifies whether incoming video plays on this stream (true) or not (false). The default value is true. If the specified stream contains only video data, NetStream.time stops incrementing when you pass false. Specifies whether incoming video plays on the stream. This method is available only to clients subscribed to the specified stream. It is not available to the publisher of the stream. Call this method before or after you call the NetStream.play() method. For example, attach this method to a button to allow users to show and hide the video. Use this method only on unicast streams that are played back from Flash Media Server. This method doesn't work on RTMFP multicast streams or when using the NetStream.appendBytes() method. resetDRMVouchers Deletes all locally cached digital rights management (DRM) voucher data.The voucher data cannot be deleted. IOErrorflash.errors:IOError Deletes all locally cached digital rights management (DRM) voucher data.

The application must re-download any required vouchers from the media rights server for the user to be able to access protected content. Calling this function is equivalent to calling the resetDRMVouchers() function of the DRMManager object.

The following example resets all DRM vouchers: NetStream.resetDRMVouchers();
flash.net.drm.DRMManager.resetDRMVouchers()
resume Resumes playback of a video stream that is paused. Resumes playback of a video stream that is paused. If the video is already playing, calling this method does nothing. close()pause()play()togglePause()seek Seeks the keyframe (also called an I-frame in the video industry) closest to the specified location.offsetNumberThe approximate time value, in seconds, to move to in a video file. With Flash Media Server, if <EnhancedSeek> is set to true in the Application.xml configuration file (which it is by default), the server generates a keyframe at offset.
  • To return to the beginning of the stream, pass 0 for offset.
  • To seek forward from the beginning of the stream, pass the number of seconds to advance. For example, to position the playhead at 15 seconds from the beginning (or the keyframe before 15 seconds), use myStream.seek(15).
  • To seek relative to the current position, pass NetStream.time + n or NetStream.time - n to seek n seconds forward or backward, respectively, from the current position. For example, to rewind 20 seconds from the current position, use NetStream.seek(NetStream.time - 20).
Seeks the keyframe (also called an I-frame in the video industry) closest to the specified location. The keyframe is placed at an offset, in seconds, from the beginning of the stream.

Video streams are usually encoded with two types of frames, keyframes (or I-frames) and P-frames. A keyframe contains an entire image, while a P-frame is an interim frame that provides additional video information between keyframes. A video stream typically has a keyframe every 10-50 frames.

Flash Media Server has several types of seek behavior: enhanced seeking and smart seeking.

Enhanced seeking

Enhanced seeking is enabled by default. To disable enhanced seeking, on Flash Media Server set the EnhancedSeek element in the Application.xml configuration file to false.

If enhanced seeking is enabled, the server generates a new keyframe at offset based on the previous keyframe and any intervening P-frames. However, generating keyframes creates a high processing load on the server and distortion might occur in the generated keyframe. If the video codec is On2, the keyframe before the seek point and any P-frames between the keyframe and the seek point are sent to the client.

If enhanced seeking is disabled, the server starts streaming from the nearest keyframe. For example, suppose a video has keyframes at 0 seconds and 10 seconds. A seek to 4 seconds causes playback to start at 4 seconds using the keyframe at 0 seconds. The video stays frozen until it reaches the next keyframe at 10 seconds. To get a better seeking experience, you need to reduce the keyframe interval. In normal seek mode, you cannot start the video at a point between the keyframes.

Smart seeking

To enable smart seeking, set NetStream.inBufferSeek to true.

Smart seeking allows Flash Player to seek within an existing back buffer and forward buffer. When smart seeking is disabled, each time seek() is called Flash Player flushes the buffer and requests data from the server. For more information, see NetStream.inBufferSeek.

Seeking in Data Generation Mode

When you call seek() on a NetStream in Data Generation Mode, all bytes passed to appendBytes() are discarded (not placed in the buffer, accumulated in the partial message FIFO, or parsed for seek points) until you call appendBytesAction(NetStreamAppendBytesAction.RESET_BEGIN) or appendBytesAction(NetStreamAppendBytesAction.RESET_SEEK) to reset the parser. For information about Data Generation Mode, see NetStream.play().

inBufferSeekbackBufferLengthbackBufferTimestep()timeplay()
send Sends a message on a published stream to all subscribing clients.handlerNameStringThe message to send; also the name of the ActionScript handler to receive the message. The handler name can be only one level deep (that is, it can't be of the form parent/child) and is relative to the stream object. Do not use a reserved term for a handler name. For example, using "close" as a handler name causes the method to fail. With Flash Media Server, use @setDataFrame to add a keyframe of metadata to a live stream or @clearDataFrame to remove a keyframe. argumentsOptional arguments that can be of any type. They are serialized and sent over the connection, and the receiving handler receives them in the same order. If a parameter is a circular object (for example, a linked list that is circular), the serializer handles the references correctly. With Flash Media Server, if @setDataFrame is the first argument, use onMetaData as the second argument; for the third argument, pass an instance of Object or Array that has the metadata set as properties. See the Flash Media Server Developer Guide for a list of suggested property names. With @clearDataFrame as the first argument, use onMetaData as the second argument and no third argument. Sends a message on a published stream to all subscribing clients. This method is available only to the publisher of the specified stream. This method is available for use with Flash Media Server only. To process and respond to this message, create a handler on the NetStream object, for example, ns.HandlerName.

Flash Player or AIR does not serialize methods or their data, object prototype variables, or non-enumerable variables. For display objects, Flash Player or AIR serializes the path but none of the data.

You can call the send() method to add data keyframes to a live stream published to Flash Media Server. A data keyframe is a message a publisher adds to a live stream. Data keyframes are typically used to add metadata to a live stream before data is captured for the stream from camera and microphone. A publisher can add a data keyframe at any time while the live stream is being published. The data keyframe is saved in the server's memory as long as the publisher is connected to the server.

Clients who are subscribed to the live stream before a data keyframe is added receive the keyframe as soon as it is added. Clients who subscribe to the live stream after the data keyframe is added receive the keyframe when they subscribe.

To add a keyframe of metadata to a live stream sent to Flash Media Server, use @setDataFrame as the handler name, followed by two additional arguments, for example:

var ns:NetStream = new NetStream(nc); ns.send("@setDataFrame", "onMetaData", metaData);

The @setDataFrame argument refers to a special handler built in to Flash Media Server. The onMetaData argument is the name of a callback function in your client application that listens for the onMetaData event and retrieves the metadata. The third item, metaData, is an instance of Object or Array with properties that define the metadata values.

Use @clearDataFrame to clear a keyframe of metadata that has already been set in the stream:

ns.send("@clearDataFrame", "onMetaData");
The following example creates two NetStream objects. One is used to publish a live stream to the server, while the other subscribes to the stream. package { import flash.display.Sprite; import flash.net.NetConnection; import flash.net.NetStream; import flash.events.NetStatusEvent; import flash.media.Video; import flash.utils.setTimeout; public class TestExample extends Sprite { var nc:NetConnection = new NetConnection(); var ns1:NetStream; var ns2:NetStream; var vid:Video = new Video(300,300); var obj:Object = new Object(); public function TestExample() { nc.objectEncoding = 0; nc.addEventListener("netStatus", onNCStatus); nc.connect("rtmp://localhost/FlashVideoApp"); addChild(vid); } function onNCStatus(event:NetStatusEvent):void { switch (event.info.code) { case "NetConnection.Connect.Success": trace("You've connected successfully"); ns1 = new NetStream(nc); ns2 = new NetStream(nc); ns1.client = new CustomClient(); ns1.publish("dummy", "live"); ns2.play("dummy"); ns2.client = new CustomClient(); vid.attachNetStream(ns2); setTimeout(sendHello, 3000); break; case "NetStream.Publish.BadName": trace("Please check the name of the publishing stream" ); break; } } function sendHello():void { ns1.send("myFunction", "hello"); } } } class CustomClient { public function myFunction(event:String):void { trace(event); } } The following example creates metadata and adds it to a live stream: private function netStatusHandler(event:NetStatusEvent):void { switch (event.info.code) { case "NetStream.Publish.Start": var metaData:Object = new Object(); metaData.title = "myStream"; metaData.width = 400; metaData.height = 200; ns.send("&#64;setDataFrame", "onMetaData", metaData); ns.attachCamera( Camera.getCamera() ); ns.attachAudio( Microphone.getMicrophone() ); } } To respond to a data keyframe added to a video, the client needs to define an onMetaData event handler. The onMetaData event handler is not registered with addEventListener(), but instead is a callback function with the name onMetaData, for example: public function onMetaData(info:Object):void { trace("width: " + info.width); trace("height: " + info.height); } This example shows how to create a playlist on the server: // Create a NetStream for playing var my_ns:NetStream = new NetStream(my_nc); my_video.attachNetStream(my_ns); // Play the stream record1 my_ns.play("record1", 0, -1, true); // Switch to the stream live1 and play for 5 seconds. // Since reset is false, live1 will start to play after record1 is done. my_ns.play("live1", -1 , 5, false); If the recorded video file contains only data messages, you can either play the video file at the speed at which it was originally recorded, or you can get the data messages all at once. //To play at normal speed var my_ns:NetStream = new NetStream(my_nc); my_ns.play("log", 0, -1); //To get the data messages all at once my_ns.play("log", 0, -1, 3);
clientdataReliableplay()
setDRMAuthenticationCredentials Sets the DRM authentication credentials needed for viewing the underlying encrypted content.userNameStringA valid user name credential. passwordStringThe password credential corresponding to the user name provided. typeStringA string that specifies what type of authentication credentials are provided. Valid values are "drm" and "proxy". The default value is "drm".
  • With "drm" authentication type, the credentials provided are authenticated against Flash Access.
  • With "proxy" authentication type, the credentials provided are authenticated against the proxy server and must match those required by the proxy server. For example, the "proxy" option allows the application to authenticate against a proxy server if an enterprise requires such a step before the user can access the Internet. Unless anonymous authentication is used, after the proxy authentication, the user still needs to authenticate against Flash Access in order to obtain the voucher and play the content. You can use setDRMAuthenticationcredentials() a second time, with "drm" option, to authenticate against Flash Access.
Sets the DRM authentication credentials needed for viewing the underlying encrypted content.

The setDRMAuthenticationCredentials() method must provide credentials that match those known and accepted by the content provider or the proxy server. These are the same credentials used by the user when obtaining the permission to view the content.

flash.events.DRMAuthenticateEvent
step Steps forward or back the specified number of frames, relative to the currently displayed frame.framesint Steps forward or back the specified number of frames, relative to the currently displayed frame. Specify a positive number to step forward and a negative number to step in reverse. Call this method to create accurate fast forward or rewind functionality.

This method is available only when data is streaming from Flash Media Server 3.5.3 or higher and when NetStream.inBufferSeek is true. Also, the target frame must be in the buffer. For example, if the currently displayed frame is frame number 120 and you specify a value of 1000, the method fails if frame number 1120 is not in the buffer.

This method is intended to be used with the pause() or togglePause() methods. If you step 10 frames forward or backward during playback without pausing, you may not notice the steps or they'll look like a glitch. Also, when you call pause() or togglePause the audio is suppressed.

If the call to NetStream.step() is successful, a NetStatusEvent is sent with "NetStream.Step.Notify" as the value of the info object's code property.

inBufferSeekbackBufferTimebackBufferLengthbufferTimebufferLengthstep()seek()
togglePause Pauses or resumes playback of a stream. Pauses or resumes playback of a stream. The first time you call this method, it pauses play; the next time, it resumes play. You could use this method to let users pause or resume playback by pressing a single button. close()play()pause()resume()CONNECT_TO_FMS A static object used as a parameter to the constructor for a NetStream instance.connectToFMSString A static object used as a parameter to the constructor for a NetStream instance. It is the default value of the second parameter in the NetStream constructor; it is not used by the application for progressive media playback. When used, this parameter causes the constructor to make a connection to a Flash Media Server instance. DIRECT_CONNECTIONS Creates a peer-to-peer publisher connection.directConnectionsString Creates a peer-to-peer publisher connection. Pass this string for the second (optional) parameter to the constructor for a NetStream instance. With this string, an application can create a NetStream connection for the purposes of publishing audio and video to clients. audioReliable For RTMFP connections, specifies whether audio is sent with full reliability.Boolean For RTMFP connections, specifies whether audio is sent with full reliability. When TRUE, all audio transmitted over this NetStream is fully reliable. When FALSE, the audio transmitted is not fully reliable, but instead is retransmitted for a limited time and then dropped. You can use the FALSE value to reduce latency at the expense of audio quality.

If you try to set this property to FALSE on a network protocol that does not support partial reliability, the attempt is ignored and the property is set to TRUE.

dataReliablevideoReliable
audioSampleAccess For RTMFP connections, specifies whether peer-to-peer subscribers on this NetStream are allowed to capture the audio stream.Boolean For RTMFP connections, specifies whether peer-to-peer subscribers on this NetStream are allowed to capture the audio stream. When FALSE, subscriber attempts to capture the audio stream show permission errors. videoSampleAccessbackBufferLength The number of seconds of previously displayed data that currently cached for rewinding and playback.Number The number of seconds of previously displayed data that currently cached for rewinding and playback.

This property is available only when data is streaming from Flash Media Server 3.5.3 or higher; for more information on Flash Media Server, see the class description.

To specify how much previously displayed data is cached, use the Netstream.backBufferTime property.

To prevent data from being cached, set the Netstream.inBufferSeek property to FALSE.

backBufferTimeinBufferSeek
backBufferTime Specifies how much previously displayed data Flash Player tries to cache for rewinding and playback, in seconds.Number Specifies how much previously displayed data Flash Player tries to cache for rewinding and playback, in seconds. The default value is 30 seconds for desktop applications and 3 seconds for mobile applications.

This property is available only when data is streaming from Flash Media Server version 3.5.3 or later; for more information on Flash Media Server, see the class description.

Using this property improves performance for rewind operations, as data that has already been displayed isn't retrieved from the server again. Instead, the stream begins replaying from the buffer. During playback, data continues streaming from the server until the buffer is full.

If the rewind position is farther back than the data in the cache, the buffer is flushed; the data then starts streaming from the server at the requested position.

To use this property set the Netstream.inBufferSeek property to TRUE.

backBufferLengthbufferTimeinBufferSeek
bufferLength The number of seconds of data currently in the buffer.Number The number of seconds of data currently in the buffer. You can use this property with the bufferTime property to estimate how close the buffer is to being full — for example, to display feedback to a user who is waiting for data to be loaded into the buffer. backBufferLengthbufferTimebytesLoadedbufferTimeMax Specifies a maximum buffer length for live streaming content, in seconds.Number Specifies a maximum buffer length for live streaming content, in seconds. The default value is 0. Buffer length can grow over time due to networking and device issues (such as clock drift between sender and receiver). Set this property to cap the buffer length for live applications such as meetings and surveillance.

When bufferTimeMax > 0 and bufferLength >= bufferTimeMax, audio plays faster until bufferLength reaches bufferTime. If a live stream is video-only, video plays faster until bufferLength reaches bufferTime.

Depending on how much playback is lagging (the difference between bufferLength and bufferTime), Flash Player controls the rate of catch-up between 1.5% and 6.25%. If the stream contains audio, faster playback is achieved by frequency domain downsampling which minimizes audible distortion.

Set the bufferTimeMax property to enable live buffered stream catch-up in the following cases:

  • Streaming live media from Flash Media Server.
  • Streaming live media in Data Generation Mode (NetStream.appendBytes()).
bufferLengthbufferTime
bufferTime Specifies how long to buffer messages before starting to display the stream.Number Specifies how long to buffer messages before starting to display the stream.

The default value is 0.1 (one-tenth of a second). To determine the number of seconds currently in the buffer, use the bufferLength property.

To play a server-side playlist, set bufferTime to at least 1 second. If you experience playback issues, increase the length of bufferTime.

Recorded content To avoid distortion when streaming pre-recorded (not live) content, do not set the value of Netstream.bufferTime to 0. By default, the application uses an input buffer for pre-recorded content that queues the media data and plays the media properly. For pre-recorded content, use the default setting or increase the buffer time.

Live content When streaming live content, set the bufferTime property to 0.

Starting with Flash Player 9.0.115.0, Flash Player no longer clears the buffer when NetStream.pause() is called. Before Flash Player 9.0.115.0, Flash Player waited for the buffer to fill up before resuming playback, which often caused a delay.

For a single pause, the NetStream.bufferLength property has a limit of either 60 seconds or twice the value of NetStream.bufferTime, whichever value is higher. For example, if bufferTime is 20 seconds, Flash Player buffers until NetStream.bufferLength is the higher value of either 20~~2 (40), or 60. In this case it buffers until bufferLength is 60. If bufferTime is 40 seconds, Flash Player buffers until bufferLength is the higher value of 40~~2 (80), or 60. In this case it buffers until bufferLength is 80 seconds.

The bufferLength property also has an absolute limit. If any call to pause() causes bufferLength to increase more than 600 seconds or the value of bufferTime ~~ 2, whichever is higher, Flash Player flushes the buffer and resets bufferLength to 0. For example, if bufferTime is 120 seconds, Flash Player flushes the buffer if bufferLength reaches 600 seconds; if bufferTime is 360 seconds, Flash Player flushes the buffer if bufferLength reaches 720 seconds.

Tip: You can use NetStream.pause() in code to buffer data while viewers are watching a commercial, for example, and then unpause when the main video starts.

For more information about the new pause behavior, see http://www.adobe.com/go/learn_fms_smartpause_en.

Flash Media Server. The buffer behavior depends on whether the buffer time is set on a publishing stream or a subscribing stream. For a publishing stream, bufferTime specifies how long the outgoing buffer can grow before the application starts dropping frames. On a high-speed connection, buffer time is not a concern; data is sent almost as quickly as the application can buffer it. On a slow connection, however, there can be a significant difference between how fast the application buffers the data and how fast it is sent to the client.

For a subscribing stream, bufferTime specifies how long to buffer incoming data before starting to display the stream.

When a recorded stream is played, if bufferTime is 0, Flash sets it to a small value (approximately 10 milliseconds). If live streams are later played (for example, from a playlist), this buffer time persists. That is, bufferTime remains nonzero for the stream.

backBufferTimebufferLengthbufferTimeMaxtime
bytesLoaded The number of bytes of data that have been loaded into the application.uint The number of bytes of data that have been loaded into the application. You can use this property with the bytesTotal property to estimate how close the buffer is to being full — for example, to display feedback to a user who is waiting for data to be loaded into the buffer. bytesTotalbufferLengthbytesTotal The total size in bytes of the file being loaded into the application.uint The total size in bytes of the file being loaded into the application. bytesLoadedbufferTimecheckPolicyFile Specifies whether the application tries to download a cross-domain policy file from the loaded video file's server before beginning to load the video file.Boolean Specifies whether the application tries to download a cross-domain policy file from the loaded video file's server before beginning to load the video file. Use this property for progressive video download, and to load files that are outside the calling SWF file's own domain. This property is ignored when you are using RTMP.

Set this property to true to call BitmapData.draw() on a video file loaded from a domain outside that of the calling SWF. The BitmapData.draw() method provides pixel-level access to the video. If you call BitmapData.draw() without setting the checkPolicyFile property to true at loading time, you can get a SecurityError exception because the required policy file was not downloaded.

Do not set this property to true unless you want pixel-level access to the video you are loading. Checking for a policy file consumes network bandwidth and can delay the start of your download.

When you call the NetStream.play() method with checkPolicyFile set to true, Flash Player or the AIR runtime must either successfully download a relevant cross-domain policy file or determine that no such policy file exists before it begins downloading. To verify the existence of a policy file, Flash Player or the AIR runtime performs the following actions, in this order:

  1. The application considers policy files that have already been downloaded.
  2. The application tries to download any pending policy files specified in calls to the Security.loadPolicyFile() method.
  3. The application tries to download a policy file from the default location that corresponds to the URL you passed to NetStream.play(), which is /crossdomain.xml on the same server as that URL.

In all cases, Flash Player or Adobe AIR requires that an appropriate policy file exist on the video's server, that it provide access to the object at the URL you passed to play() based on the policy file's location, and that it allow the domain of the calling code's file to access the video, through one or more <allow-access-from> tags.

If you set checkPolicyFile to true, the application waits until the policy file is verified before downloading the video. Wait to perform any pixel-level operations on the video data, such as calling BitmapData.draw(), until you receive onMetaData or NetStatus events from your NetStream object.

If you set checkPolicyFile to true but no relevant policy file is found, you won't receive an error until you perform an operation that requires a policy file, and then the application throws a SecurityError exception.

Be careful with checkPolicyFile if you are downloading a file from a URL that uses server-side HTTP redirects. The application tries to retrieve policy files that correspond to the initial URL that you specify in NetStream.play(). If the final file comes from a different URL because of HTTP redirects, the initially downloaded policy files might not be applicable to the file's final URL, which is the URL that matters in security decisions.

For more information on policy files, see "Website controls (policy files)" in the ActionScript 3.0 Developer's Guide and the Flash Player Developer Center Topic: Security.

flash.display.BitmapData.draw()flash.system.Security.loadPolicyFile()netStatusonMetaDataplay()
client Specifies the object on which callback methods are invoked to handle streaming or F4V/FLV file data.ObjectThe client property must be set to a non-null object. TypeErrorTypeError Specifies the object on which callback methods are invoked to handle streaming or F4V/FLV file data. The default object is this, the NetStream object being created. If you set the client property to another object, callback methods are invoked on that other object. The NetStream.client object can call the following functions and receive an associated data object: onCuePoint(), onImageData(), onMetaData(), onPlayStatus(), onSeekPoint(), onTextData(), and onXMPData().

To associate the client property with an event handler:

  1. Create an object and assign it to the client property of the NetStream object: var customClient:Object = new Object(); my_netstream.client = customClient;
  2. Assign a handler function for the desired data event as a property of the client object: customClient.onImageData = onImageDataHandler;
  3. Write the handler function to receive the data event object, such as: public function onImageDataHandler(imageData:Object):void { trace("imageData length: " + imageData.data.length); }

When data is passed through the stream or during playback, the data event object (in this case the imageData object) is populated with the data. See the onImageData description, which includes a full example of an object assigned to the client property.

To associate the client property with a subclass:

  1. Create a subclass with a handler function to receive the data event object: class CustomClient { public function onMetaData(info:Object):void { trace("metadata: duration=" + info.duration + " framerate=" + info.framerate); }
  2. Assign an instance of the subclass to the client property of the NetStream object: my_netstream.client = new CustomClient();

When data is passed through the stream or during playback, the data event object (in this case the info object) is populated with the data. See the class example at the end of the NetStream class, which shows the assignment of a subclass instance to the client property.

onCuePointonImageDataonMetaDataonPlayStatusonSeekPointonTextData
currentFPS The number of frames per second being displayed.Number The number of frames per second being displayed. If you are exporting video files to be played back on a number of systems, you can check this value during testing to help you determine how much compression to apply when exporting the file. dataReliable For RTMFP connections, specifies whether NetStream.send() calls are sent with full reliability.Boolean For RTMFP connections, specifies whether NetStream.send() calls are sent with full reliability. When TRUE, NetStream.send() calls that are transmitted over this NetStream are fully reliable. When FALSE, NetStream.send() calls are not transmitted with full reliability, but instead are retransmitted for a limited time and then dropped. You can set this value to FALSE to reduce latency at the expense of data quality.

If you try to set this property to FALSE on a network protocol that does not support partial reliability, the attempt is ignored and the property is set to TRUE.

audioReliablesend()videoReliable
farID For RTMFP connections, the identifier of the far end that is connected to this NetStream instance.String For RTMFP connections, the identifier of the far end that is connected to this NetStream instance. farNonce For RTMFP and RTMPE connections, a value chosen substantially by the other end of this stream, unique to this connection.String For RTMFP and RTMPE connections, a value chosen substantially by the other end of this stream, unique to this connection. This value appears to the other end of the stream as its nearNonce value. inBufferSeek Specifies whether displayed data is cached for smart seeking (TRUE), or not (FALSE).Boolean Specifies whether displayed data is cached for smart seeking (TRUE), or not (FALSE). The default value is FALSE.

Flash Media Server 3.5.3 and Flash Player 10.1 work together to support smart seeking. Smart seeking uses back and forward buffers to seek without requesting data from the server. Standard seeking flushes buffered data and asks the server to send new data based on the seek time.

Call NetStream.step() to step forward and backward a specified number of frames. Call NetStream.seek() to seek forward and backward a specified number of seconds.

Smart seeking reduces server load and improves seeking performance. Set inBufferSeek=true and call step() and seek() to create:

  • Client-side DVR functionality. Seek within the client-side buffer instead of going to the server for delivery of new video.
  • Trick modes. Create players that step through frames, fast-forward, fast-rewind, and advance in slow-motion.

When inBufferSeek=true and a call to NetStream.seek() is successful, the NetStatusEvent info.description property contains the string "client-inBufferSeek".

When a call to NetStream.step() is successful, the NetStatusEvent info.code property contains the string "NetStream.Step.Notify".

backBufferTimebackBufferLengthbufferTimebufferLengthstep()seek()
info Returns a NetStreamInfo object whose properties contain statistics about the quality of service.flash.net:NetStreamInfo Returns a NetStreamInfo object whose properties contain statistics about the quality of service. The object is a snapshot of the current state. flash.net.NetStreamInfoliveDelay The number of seconds of data in the subscribing stream's buffer in live (unbuffered) mode.Number The number of seconds of data in the subscribing stream's buffer in live (unbuffered) mode. This property specifies the current network transmission delay (lag time).

This property is intended primarily for use with a server such as Flash Media Server; for more information, see the class description.

You can get the value of this property to roughly gauge the transmission quality of the stream and communicate it to the user.

maxPauseBufferTime Specifies how long to buffer messages during pause mode, in seconds.Number Specifies how long to buffer messages during pause mode, in seconds. This property can be used to limit how much buffering is done during pause mode. As soon as the value of NetStream.bufferLength reaches this limit, it stops buffering.

If this value is not set, it defaults the limit to 60 seconds or twice the value of NetStream.bufferTime on each pause, whichever is higher.

bufferTime
multicastAvailabilitySendToAll For RTMFP connections, specifies whether peer-to-peer multicast fragment availability messages are sent to all peers or to just one peer.Boolean For RTMFP connections, specifies whether peer-to-peer multicast fragment availability messages are sent to all peers or to just one peer. A value of TRUE specifies that the messages are sent to all peers once per specified interval. A value of FALSE specifies that the messages are sent to just one peer per specified interval. The interval is determined by the multicastAvailabilityUpdatePeriod property. multicastAvailabilityUpdatePeriodmulticastAvailabilityUpdatePeriod For RTMFP connections, specifies the interval in seconds between messages sent to peers informing them that the local node has new peer-to-peer multicast media fragments available.Number For RTMFP connections, specifies the interval in seconds between messages sent to peers informing them that the local node has new peer-to-peer multicast media fragments available. Larger values can increase batching efficiency and reduce control overhead, but they can lower quality on the receiving end by reducing the amount of time available to retrieve fragments before they are out-of-window. Lower values can reduce latency and improve quality, but they increase control overhead. multicastAvailabilitySendToAllmulticastFetchPeriodmulticastWindowDurationmulticastFetchPeriod For RTMFP connections, specifies the time in seconds between when the local node learns that a peer-to-peer multicast media fragment is available and when it tries to fetch it from a peer.Number For RTMFP connections, specifies the time in seconds between when the local node learns that a peer-to-peer multicast media fragment is available and when it tries to fetch it from a peer. This value gives an opportunity for the fragment to be proactively pushed to the local node before a fetch from a peer is attempted. It also allows for more than one peer to announce availability of the fragment, so the fetch load can be spread among multiple peers.

Larger values can improve load balancing and fairness in the peer-to-peer mesh, but reduce the available multicastWindowDuration and increase latency. Smaller values can reduce latency when fetching is required, but might increase duplicate data reception and reduce peer-to-peer mesh load balance.

multicastAvailabilityUpdatePeriodmulticastWindowDuration
multicastInfo For RTMFP connections, returns a NetStreamMulticastInfo object whose properties contain statistics about the quality of service.flash.net:NetStreamMulticastInfo For RTMFP connections, returns a NetStreamMulticastInfo object whose properties contain statistics about the quality of service. The object is a snapshot of the current state. flash.net.NetStreamMulticastInfomulticastPushNeighborLimit For RTMFP connections, specifies the maximum number of peers to which to proactively push multicast media.Number For RTMFP connections, specifies the maximum number of peers to which to proactively push multicast media. multicastRelayMarginDuration For RTMFP connections, specifies the duration in seconds that peer-to-peer multicast data remains available to send to peers that request it beyond a specified duration.Number For RTMFP connections, specifies the duration in seconds that peer-to-peer multicast data remains available to send to peers that request it beyond a specified duration. The duration is specified by the multicastWindowDuration property. multicastWindowDurationmulticastWindowDuration For RTMFP connections, specifies the duration in seconds of the peer-to-peer multicast reassembly window.Number For RTMFP connections, specifies the duration in seconds of the peer-to-peer multicast reassembly window. Shorter values reduce latency but may reduce quality by not allowing enough time to obtain all of the fragments. Conversely, larger values may increase quality by providing more time to obtain all of the fragments, with a corresponding increase in latency. multicastRelayMarginDurationnearNonce For RTMFP and RTMPE connections, a value chosen substantially by this end of the stream, unique to this connection.String For RTMFP and RTMPE connections, a value chosen substantially by this end of the stream, unique to this connection. This value appears to the other end of the stream as its farNonce value. objectEncoding The object encoding (AMF version) for this NetStream object.uint The object encoding (AMF version) for this NetStream object. The NetStream object inherits its objectEncoding value from the associated NetConnection object. 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. For more information, see the objectEncoding property description in the NetConnection class.

The value of this property depends on whether the stream is local or remote. Local streams, where null was passed to the NetConnection.connect() method, return the value of NetConnection.defaultObjectEncoding. Remote streams, where you are connecting to a server, return the object encoding of the connection to the server.

If you try to read this property when not connected, or if you try to change this property, the application throws an exception.

flash.net.NetConnection.objectEncoding
peerStreams An object that holds all of the subscribing NetStream instances that are listening to this publishing NetStream instance.Array An object that holds all of the subscribing NetStream instances that are listening to this publishing NetStream instance. soundTransform Controls sound in this NetStream object.flash.media:SoundTransform Controls sound in this NetStream object. For more information, see the SoundTransform class. flash.media.SoundTransformtime The position of the playhead, in seconds.Number The position of the playhead, in seconds.

Flash Media Server For a subscribing stream, the number of seconds the stream has been playing. For a publishing stream, the number of seconds the stream has been publishing. This number is accurate to the thousandths decimal place; multiply by 1000 to get the number of milliseconds the stream has been playing.

For a subscribing stream, if the server stops sending data but the stream remains open, the value of the time property stops advancing. When the server begins sending data again, the value continues to advance from the point at which it stopped (when the server stopped sending data).

The value of time continues to advance when the stream switches from one playlist element to another. This property is set to 0 when NetStream.play() is called with reset set to 1 or true, or when NetStream.close() is called.

bufferLengthbytesLoaded
videoReliable For RTMFP connections, specifies whether video is sent with full reliability.Boolean For RTMFP connections, specifies whether video is sent with full reliability. When TRUE, all video transmitted over this NetStream is fully reliable. When FALSE, the video transmitted is not fully reliable, but instead is retransmitted for a limited time and then dropped. You can use the FALSE value to reduce latency at the expense of video quality.

If you try to set this property to FALSE on a network protocol that does not support partial reliability, the attempt is ignored and the property is set to TRUE.

audioReliabledataReliable
videoSampleAccess For RTMFP connections, specifies whether peer-to-peer subscribers on this NetStream are allowed to capture the video stream.Boolean For RTMFP connections, specifies whether peer-to-peer subscribers on this NetStream are allowed to capture the video stream. When FALSE, subscriber attempts to capture the video stream show permission errors. audioSampleAccess
NetMonitor The NetMonitor class allows you to monitor the NetStream objects used by an application.flash.events:EventDispatcher The NetMonitor class allows you to monitor the NetStream objects used by an application.

Use the NetMonitor class to get the current list of NetStream objects in use in an application. An instance of this class dispatches a netStreamCreate event whenever a new NetStream object is created.

You can use the NetMonitor class to help track video playback and related events without regard to the specific video player being used. This facility can be helpful when implementing media measurement, analytics, and usage tracking libraries.

Note: NetStream monitoring is not supported by Flash Player in the browser on Android and Blackberry Tablet OS or by AIR on iOS.

This example demonstrates how the NetMonitor class can be used to gain access to NetStream information without intimate knowledge of the specific video player in use. Here, the MediaPlayerSprite class from the Open Screen Media Framework (OSMF) project is used, but any video player could be substituted.

You can use the Space bar to pause and unpause the video in the example and the right and left arrows to seek forward or back 30 seconds to see the effects these actions have on the dispatched events.

package { import flash.display.Sprite; import flash.display.StageAlign; import flash.display.StageScaleMode; import flash.events.KeyboardEvent; import flash.events.NetDataEvent; import flash.events.NetMonitorEvent; import flash.events.NetStatusEvent; import flash.net.NetMonitor; import flash.net.NetStream; import flash.ui.Keyboard; import org.osmf.elements.VideoElement; import org.osmf.media.MediaPlayer; import org.osmf.media.MediaPlayerSprite; import org.osmf.net.DynamicStreamingItem; import org.osmf.net.DynamicStreamingResource; public class NetMonitorExample extends Sprite { private var netmon:NetMonitor; private var mediaPlayer:MediaPlayer; public function NetMonitorExample() { //Configure stage this.stage.align = StageAlign.TOP_LEFT; this.stage.scaleMode = StageScaleMode.NO_SCALE; //Create NetMonitor object netmon = new flash.net.NetMonitor(); netmon.addEventListener(NetMonitorEvent.NET_STREAM_CREATE, newNetStream ); //Setup video player var mediaPlayerSprite:MediaPlayerSprite = new MediaPlayerSprite(); var videoElement:VideoElement = new VideoElement(); var dynResource:DynamicStreamingResource = new DynamicStreamingResource( "rtmp://cp67126.edgefcs.net/ondemand" ); dynResource.streamItems = Vector.<DynamicStreamingItem>( [ new DynamicStreamingItem( "mp4:mediapm/ovp/content/demo/video/elephants_dream/elephants_dream_768x428_24.0fps_408kbps.mp4", 408, 768, 428 ) , new DynamicStreamingItem( "mp4:mediapm/ovp/content/demo/video/elephants_dream/elephants_dream_768x428_24.0fps_608kbps.mp4", 608, 768, 428 ) , new DynamicStreamingItem( "mp4:mediapm/ovp/content/demo/video/elephants_dream/elephants_dream_1024x522_24.0fps_908kbps.mp4", 908, 1024, 522 ) , new DynamicStreamingItem( "mp4:mediapm/ovp/content/demo/video/elephants_dream/elephants_dream_1024x522_24.0fps_1308kbps.mp4", 1308, 1024, 522 ) , new DynamicStreamingItem( "mp4:mediapm/ovp/content/demo/video/elephants_dream/elephants_dream_1280x720_24.0fps_1708kbps.mp4", 1708, 1280, 720 ) ]); videoElement.resource = dynResource; addChild( mediaPlayerSprite ); mediaPlayerSprite.media = videoElement; mediaPlayer = mediaPlayerSprite.mediaPlayer; this.stage.addEventListener( KeyboardEvent.KEY_DOWN, keyControl ); } //On new NetStream private function newNetStream( event:NetMonitorEvent ):void { trace( "New Netstream object "); var stream:NetStream = event.netStream; stream.addEventListener(NetDataEvent.MEDIA_TYPE_DATA, onStreamData); stream.addEventListener(NetStatusEvent.NET_STATUS, onStatus); } //On data events from a NetStream object private function onStreamData( event:NetDataEvent ):void { trace( "Data event at " + event.timestamp ); var netStream:NetStream = event.target as NetStream; switch( event.info.handler ) { case "onMetaData": trace( "--MetaData: " + stringify( netStream.info.metaData )); break; case "onXMPData": trace( "--XMPData: " + stringify( netStream.info.xmpData )); break; default: trace( "--" + event.info.handler + ": " + stringify(event.info.args[0]) ); } } //On status events from a NetStream object private function onStatus( event:NetStatusEvent ):void { trace( "Status: " + stringify( event.info ) ); } //Utility function to print out object properties private function stringify( object:Object ):String { var string:String = ""; var prop:String; var comma:Boolean = false; for ( prop in object ) { if( comma ) string += ", "; else comma = true; if( typeof(object[prop]) == "object" ) { stringify( object[prop] ) } else string += prop + " = " + object[prop]; } return string; } //Simple keyboard control for the video player private function keyControl( event:KeyboardEvent ):void { switch ( event.keyCode ) { case Keyboard.SPACE: if( mediaPlayer.paused ) mediaPlayer.play(); else mediaPlayer.pause(); break; case Keyboard.RIGHT: mediaPlayer.seek( mediaPlayer.currentTime + 30 ); break; case Keyboard.LEFT: mediaPlayer.seek( mediaPlayer.currentTime - 30 ); break; default: //do nothing } } } }
NetStreamnetStreamCreate Dispatched when a new NetStream object is created within the security context of this NetMonitor instance.flash.events.NetMonitorEvent.NET_STREAM_CREATEflash.events.NetMonitorEvent Dispatched when a new NetStream object is created within the security context of this NetMonitor instance.

Note: if the NetStream monitoring is not supported on the current platform, netStreamCreate events are not dispatched.

listStreams Retrieves all NetStream objects belonging to this NetMonitor object's security context.Vector of NetStream objects Retrieves all NetStream objects belonging to this NetMonitor object's security context.

Avoid caching the list of NetStream objects. Maintaining a reference to these NetStream objects can introduce memory leaks into an application by preventing the garbage collector from reclaiming an object's resources when it is no longer being used.

Note: if the NetStream monitoring is not supported on the current platform, the list returned by this function is always empty.

NetStreamInfo The NetStreamInfo class specifies the various Quality of Service (QOS) statistics and other information related to a NetStream object and the underlying streaming buffer for audio, video, and data.Object The NetStreamInfo class specifies the various Quality of Service (QOS) statistics and other information related to a NetStream object and the underlying streaming buffer for audio, video, and data. A NetStreamInfo object is returned in response to the NetStream.info call, which takes a snapshot of the current QOS state and provides the QOS statistics through the NetStreamInfo properties. toString Returns a text value listing the properties of the NetStreamInfo object.A string containing the values of the properties of the NetStreamInfo object StringReturns a text value listing the properties of this NetStreamInfo object. Returns a text value listing the properties of the NetStreamInfo object. SRTT The smoothed round trip time (SRTT) for the NetStream session, in milliseconds.Number The smoothed round trip time (SRTT) for the NetStream session, in milliseconds. This property contains a valid value only for RTMFP streams. For RTMP streams, the value is 0. flash.net.NetGroupaudioBufferByteLength Provides the NetStream audio buffer size in bytes.Number Provides the NetStream audio buffer size in bytes. It specifies the buffer size for audio data in streaming media, both live and recorded. This property is like Netstream.bytesLoaded, which is used in progressive downloads. audioBufferLength Provides NetStream audio buffer size in seconds.Number Provides NetStream audio buffer size in seconds. This property extends the NetStream.bufferLength property and provides the buffer length in time specifically for audio data. audioByteCount Specifies the total number of audio bytes that have arrived in the queue, regardless of how many have been played or flushed.Number Specifies the total number of audio bytes that have arrived in the queue, regardless of how many have been played or flushed. You can use this value to calculate the incoming audio data rate, using the metric of your choice, by creating a timer and calculating the difference in values in successive timer calls. Alternatively, use audioBytesPerSecond. audioBytesPerSecondaudioBytesPerSecond Specifies the rate at which the NetStream audio buffer is filled in bytes per second.Number Specifies the rate at which the NetStream audio buffer is filled in bytes per second. The value is calculated as a smooth average for the audio data received in the last second. audioLossRate Specifies the audio loss for the NetStream session.Number Specifies the audio loss for the NetStream session. This value returns a valid value only for RTMFP streams and would return 0 for RTMP streams. Loss rate is defined as the ratio of lost messages to total messages. byteCount Specifies the total number of bytes that have arrived into the queue, regardless of how many have been played or flushed.Number Specifies the total number of bytes that have arrived into the queue, regardless of how many have been played or flushed. You can use this value to calculate the incoming data rate, using the metric of your choice, by creating a timer and calculating the difference in values in successive timer calls. Alternatively, use currentBytesPerSecond. currentBytesPerSecondcurrentBytesPerSecond Specifies the rate at which the NetStream buffer is filled in bytes per second.Number Specifies the rate at which the NetStream buffer is filled in bytes per second. The value is calculated as a smooth average for the total data received in the last second. dataBufferByteLength Provides the NetStream data buffer size in bytes.Number Provides the NetStream data buffer size in bytes. It specifies the buffer size for data messages in streaming media, both live and recorded. This property is like Netstream.bytesLoaded, which is used in progressive downloads. dataBufferLength Provides NetStream data buffer size in seconds.Number Provides NetStream data buffer size in seconds. This property extends the NetStream.bufferLength property and provides the buffer length in time specifically for data messages. dataByteCount Specifies the total number of bytes of data messages that have arrived in the queue, regardless of how many have been played or flushed.Number Specifies the total number of bytes of data messages that have arrived in the queue, regardless of how many have been played or flushed. You can use this value to calculate the incoming data-messages rate, using the metric of your choice, by creating a timer and calculating the difference in values in successive timer calls. Alternatively, use dataBytesPerSecond. dataBytesPerSeconddataBytesPerSecond Specifies the rate at which the NetStream data buffer is filled in bytes per second.Number Specifies the rate at which the NetStream data buffer is filled in bytes per second. The value is calculated as a smooth average for the data messages received in the last second. droppedFrames Returns the number of video frames dropped in the current NetStream playback session.Number Returns the number of video frames dropped in the current NetStream playback session.

In recorded streaming or progressive download, if the video is a high-quality or high-resolution, high-bitrate video, the decoder can lag behind in decoding the required number of frames per second if it does not have adequate system CPU resources. In live streaming, the buffer drops video frames if the latency is too high. This property specifies the number of frames that were dropped and not presented normally.

isLive Whether the media being played is recorded or live.Boolean Whether the media being played is recorded or live. This property is relevant for RTMP streaming only. For progressive download and HTTP Dynamic Streaming the property is always false.

Note: This property is always false in Flash Player in the browser on Android and Blackberry Tablet OS or in AIR on iOS.

maxBytesPerSecond Specifies the maximum rate at which the NetStream buffer is filled in bytes per second.Number Specifies the maximum rate at which the NetStream buffer is filled in bytes per second. This value provides information about the capacity of the client network based on the last messages received by the NetStream object. Depending on the size of the buffer specified in NetStream.bufferTime and the bandwidth available on the client, Flash Media Server fills the buffer in bursts. This property provides the maximum rate at which the client buffer is filled. metaData The most recent metadata object associated with the media being played.Object The most recent metadata object associated with the media being played.

Note: This property is always null in Flash Player in the browser on Android and Blackberry Tablet OS or in AIR on iOS.

playbackBytesPerSecond Returns the stream playback rate in bytes per second.Number Returns the stream playback rate in bytes per second. The playback buffer can contain content of various playlists. This property provides the playback rate that closely matches the bit rate of the currently playing stream. resourceName The resource name used when NetStream.play() was called.StringThe resource name used when NetStream.play() was called. The resource name used when NetStream.play() was called. This property contains the full URL for progressive download, the resource name for RTMP streaming and null for HTTP streaming.

Note: This property is always null in Flash Player in the browser on Android and Blackberry Tablet OS or in AIR on iOS.

flash.media.NetStream.play()
uri The URI used when NetConnection.connect() was called.StringThe URI used when NetConnection.connect() was called. The URI used when NetConnection.connect() was called. This is null for progressive download or HTTP streaming.

Note: This property is always null in Flash Player in the browser on Android and Blackberry Tablet OS or in AIR on iOS.

flash.media.NetConnection.uri
videoBufferByteLength Provides the NetStream video buffer size in bytes.Number Provides the NetStream video buffer size in bytes. It specifies the buffer size for video data in streaming media, both live and recorded. This property is like Netstream.bytesLoaded, which is used in progressive downloads. videoBufferLength Provides NetStream video buffer size in seconds.Number Provides NetStream video buffer size in seconds. This property extends the NetStream.bufferLength property and provides the buffer length in time specifically for video data. videoByteCount Specifies the total number of video bytes that have arrived in the queue, regardless of how many have been played or flushed.Number Specifies the total number of video bytes that have arrived in the queue, regardless of how many have been played or flushed. You can use this value to calculate the incoming video data rate, using the metric of your choice, by creating a timer and calculating the difference in values in successive timer calls. Alternatively, use videoBytesPerSecond, videoBytesPerSecondvideoBytesPerSecond Specifies the rate at which the NetStream video buffer is filled in bytes per second.Number Specifies the rate at which the NetStream video buffer is filled in bytes per second. The value is calculated as a smooth average for the video data received in the last second. videoLossRate Provides the NetStream video loss rate (ratio of lost messages to total messages).Number Provides the NetStream video loss rate (ratio of lost messages to total messages).

When the message size is smaller than the maximum transmission unit (MTU), this value corresponds to the network packet loss rate.

This property returns a valid value only for RTMFP streams. For RTMP streams, it returns a value of zero. For more information, see the Flash Media Server documentation.

xmpData The most recent XMP data object associated with the media being played.Object The most recent XMP data object associated with the media being played.

Note: This property is always null in Flash Player in the browser on Android and Blackberry Tablet OS or in AIR on iOS.

URLStream The URLStream class provides low-level access to downloading URLs.flash.utils:IDataInputflash.events:EventDispatcher The URLStream class provides low-level access to downloading URLs. Data is made available to application code immediately as it is downloaded, instead of waiting until the entire file is complete as with URLLoader. The URLStream class also lets you close a stream before it finishes downloading. The contents of the downloaded file are made available as raw binary data.

The read operations in URLStream are nonblocking. This means that you must use the bytesAvailable property to determine whether sufficient data is available before reading it. An EOFError exception is thrown if insufficient data is available.

All binary data is encoded by default in big-endian format, with the most significant byte first.

The security rules that apply to URL downloading with the URLStream class are identical to the rules applied to URLLoader objects. Policy files may be downloaded as needed. Local file security rules are enforced, and security warnings are raised as needed.

The following example loads a SWF file and parses the beginning of its header to indicate compression and version number information.

To run the example, place a file named URLStreamExample.swf in the same directory as your SWF file.

package { import flash.display.Sprite; import flash.errors.*; import flash.events.*; import flash.net.URLRequest; import flash.net.URLStream; public class URLStreamExample extends Sprite { private static const ZLIB_CODE:String = "CWS"; private var stream:URLStream; public function URLStreamExample() { stream = new URLStream(); var request:URLRequest = new URLRequest("URLStreamExample.swf"); configureListeners(stream); try { stream.load(request); } catch (error:Error) { trace("Unable to load requested URL."); } } private function configureListeners(dispatcher:EventDispatcher):void { dispatcher.addEventListener(Event.COMPLETE, completeHandler); dispatcher.addEventListener(HTTPStatusEvent.HTTP_STATUS, httpStatusHandler); dispatcher.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler); dispatcher.addEventListener(Event.OPEN, openHandler); dispatcher.addEventListener(ProgressEvent.PROGRESS, progressHandler); dispatcher.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler); } private function parseHeader():void { trace("parseHeader"); trace("isCompressed: " + isCompressed()); trace("version: " + stream.readByte()); } private function isCompressed():Boolean { return (stream.readUTFBytes(3) == ZLIB_CODE); } private function completeHandler(event:Event):void { trace("completeHandler: " + event); parseHeader(); } private function openHandler(event:Event):void { trace("openHandler: " + event); } private function progressHandler(event:Event):void { trace("progressHandler: " + event); } private function securityErrorHandler(event:SecurityErrorEvent):void { trace("securityErrorHandler: " + event); } private function httpStatusHandler(event:HTTPStatusEvent):void { trace("httpStatusHandler: " + event); } private function ioErrorHandler(event:IOErrorEvent):void { trace("ioErrorHandler: " + event); } } }
URLLoaderURLRequestprogress Dispatched when data is received as the download operation progresses.flash.events.ProgressEvent.PROGRESSflash.events.ProgressEvent Dispatched when data is received as the download operation progresses. Data that has been received can be read immediately using the methods of the URLStream class. URLStream.load()open Dispatched when a load operation starts.flash.events.Event.OPENflash.events.Event Dispatched when a load operation starts. URLStream.load()ioError Dispatched when an input/output error occurs that causes a load operation to fail.flash.events.IOErrorEvent.IO_ERRORflash.events.IOErrorEvent Dispatched when an input/output error occurs that causes a load operation to fail. URLStream.load()httpResponseStatus Dispatched if a call to the URLStream.load() method attempts to access data over HTTP and Adobe AIR is able to detect and return the status code for the request.flash.events.HTTPStatusEvent.HTTP_RESPONSE_STATUSflash.events.HTTPStatusEvent Dispatched if a call to the URLStream.load() method attempts to access data over HTTP and Adobe AIR is able to detect and return the status code for the request.

If a URLStream object registers for an httpStatusEvent event, error responses are delivered as though they are content. So instead of dispatching an ioError event, the URLStream dispatches progress and complete events as the error data is loaded into the URLStream.

URLStream.load()
httpStatus Dispatched if a call to URLStream.load() attempts to access data over HTTP, and Flash Player or Adobe AIR is able to detect and return the status code for the request.flash.events.HTTPStatusEvent.HTTP_STATUSflash.events.HTTPStatusEvent Dispatched if a call to URLStream.load() attempts to access data over HTTP, and Flash Player or Adobe AIR is able to detect and return the status code for the request. (Some browser environments may not be able to provide this information.) Note that the httpStatus (if any) will be sent before (and in addition to) any complete or error event. URLStream.load()securityError Dispatched if a call to URLStream.load() attempts to load data from a server outside the security sandbox.flash.events.SecurityErrorEvent.SECURITY_ERRORflash.events.SecurityErrorEvent Dispatched if a call to URLStream.load() attempts to load data from a server outside the security sandbox. URLStream.load()complete Dispatched when data has loaded successfully.flash.events.Event.COMPLETEflash.events.Event Dispatched when data has loaded successfully. close Immediately closes the stream and cancels the download operation.The stream could not be closed, or the stream was not open. IOErrorflash.errors:IOError Immediately closes the stream and cancels the download operation. No data can be read from the stream after the close() method is called. load Begins downloading the URL specified in the request parameter.URLRequest.requestHeader objects may not contain certain prohibited HTTP request headers. For more information, see the URLRequestHeader class description. ArgumentErrorArgumentErrorThis error can occur for the following reasons:
  1. Flash Player or Adobe AIR cannot convert the URLRequest.data parameter from UTF8 to MBCS. This error is applicable if the URLRequest object passed to load() is set to perform a GET operation and if System.useCodePage is set to true.
  2. Flash Player or Adobe AIR cannot allocate memory for the POST data. This error is applicable if the URLRequest object passed to load is set to perform a POST operation.
MemoryErrorflash.errors:MemoryError
Local untrusted SWF files may not communicate with the Internet. This may be worked around by reclassifying this SWF file as local-with-networking or trusted. SecurityErrorSecurityErrorYou are trying to connect to a commonly reserved port. For a complete list of blocked ports, see "Restricting Networking APIs" in the ActionScript 3.0 Developer's Guide. SecurityErrorSecurityErrorrequestflash.net:URLRequestA URLRequest object specifying the URL to download. If the value of this parameter or the URLRequest.url property of the URLRequest object passed are null, the application throws a null pointer error.
Begins downloading the URL specified in the request parameter.

Note: If a file being loaded contains non-ASCII characters (as found in many non-English languages), it is recommended that you save the file with UTF-8 or UTF-16 encoding, as opposed to a non-Unicode format like ASCII.

If the loading operation fails immediately, an IOError or SecurityError (including the local file security error) exception is thrown describing the failure. Otherwise, an open event is dispatched if the URL download starts downloading successfully, or an error event is dispatched if an error occurs.

By default, the calling SWF file and the URL you load must be in exactly the same domain. For example, a SWF file at www.adobe.com can load data only from sources that are also at www.adobe.com. To load data from a different domain, place a URL policy file on the server hosting the data.

In Flash Player, you cannot connect to commonly reserved ports. For a complete list of blocked ports, see "Restricting Networking APIs" in the ActionScript 3.0 Developer's Guide.

In Flash Player, you can prevent a SWF file from using this method by setting the allowNetworking parameter of the the object and embed tags in the HTML page that contains the SWF content.

In Flash Player 10 and later, and in AIR 1.5 and later, if you use a multipart Content-Type (for example "multipart/form-data") that contains an upload (indicated by a "filename" parameter in a "content-disposition" header within the POST body), the POST operation is subject to the security rules applied to uploads:

  • The POST operation must be performed in response to a user-initiated action, such as a mouse click or key press.
  • If the POST operation is cross-domain (the POST target is not on the same server as the SWF file that is sending the POST request), the target server must provide a URL policy file that permits cross-domain access.

Also, for any multipart Content-Type, the syntax must be valid (according to the RFC2046 standards). If the syntax appears to be invalid, the POST operation is subject to the security rules applied to uploads.

These rules also apply to AIR content in non-application sandboxes. However, in Adobe AIR, content in the application sandbox (content installed with the AIR application) are not restricted by these security limitations.

For more information related to security, see The Flash Player Developer Center Topic: Security.

In AIR, a URLRequest object can register for the httpResponse status event. Unlike the httpStatus event, the httpResponseStatus event is delivered before any response data. Also, the httpResponseStatus event includes values for the responseHeaders and responseURL properties (which are undefined for an httpStatus event. Note that the httpResponseStatus event (if any) will be sent before (and in addition to) any complete or error event.

If there is an httpResponseStatus event listener, the body of the response message is always sent; and HTTP status code responses always results in a complete event. This is true in spite of whether the HTTP response status code indicates a success or an error.

In AIR, if there is no httpResponseStatus event listener, the behavior differs based on the SWF version:

  • For SWF 9 content, the body of the HTTP response message is sent only if the HTTP response status code indicates success. Otherwise (if there is an error), no body is sent and the URLRequest object dispatches an IOError event.
  • For SWF 10 content, the body of the HTTP response message is always sent. If there is an error, the URLRequest object dispatches an IOError event.
completeflash.events:EventDispatched after data has loaded successfully. If there is a httpResponseStatus event listener, the URLRequest object also dispatches a complete event whether the HTTP response status code indicates a success or an error. Dispatched after data has loaded successfully.httpStatusflash.events:HTTPStatusEventIf access is by HTTP and the current environment supports obtaining status codes, you may receive these events in addition to any complete or error event. If access is by HTTP and the current environment supports obtaining status codes, you may receive these events in addition to any complete or error event.httpResponseStatusflash.events:HTTPStatusEventDispatched if a call to the load() method attempts to access data over HTTP and Adobe AIR is able to detect and return the status code for the request. Dispatched if a call to the load() method attempts to access data over HTTP and Adobe AIR is able to detect and return the status code for the request.ioErrorflash.events:IOErrorEventThe load operation could not be completed. The load operation could not be completed.openflash.events:EventDispatched when a load operation starts. Dispatched when a load operation starts.securityErrorflash.events:SecurityErrorEventA load operation attempted to retrieve data from a server outside the caller's security sandbox. This may be worked around using a policy file on the server. A load operation attempted to retrieve data from a server outside the caller's security sandbox.
readBoolean Reads a Boolean value from the stream.There is insufficient data available to read. If a local SWF file triggers a security warning, Flash Player prevents the URLStream data from being available to ActionScript. When this happens, the bytesAvailable property returns 0 even if data has been received, and any of the read methods throws an EOFError exception. EOFErrorflash.errors:EOFErrorAn I/O error occurred on the stream, or the stream is not open. IOErrorflash.errors:IOErrorTrue is returned if the byte is nonzero, false otherwise. Boolean Reads a Boolean value from the stream. A single byte is read, and true is returned if the byte is nonzero, false otherwise. readByte Reads a signed byte from the stream.There is insufficient data available to read. If a local SWF file triggers a security warning, Flash Player prevents the URLStream data from being available to ActionScript. When this happens, the bytesAvailable property returns 0 even if data has been received, and any of the read methods throws an EOFError exception. EOFErrorflash.errors:EOFErrorAn I/O error occurred on the stream, or the stream is not open. IOErrorflash.errors:IOErrorValue in the range -128...127. int Reads a signed byte from the stream.

The returned value is in the range -128...127.

readBytes Reads length bytes of data from the stream.There is insufficient data available to read. If a local SWF file triggers a security warning, Flash Player prevents the URLStream data from being available to ActionScript. When this happens, the bytesAvailable property returns 0 even if data has been received, and any of the read methods throws an EOFError exception. EOFErrorflash.errors:EOFErrorAn I/O error occurred on the stream, or the stream is not open. IOErrorflash.errors:IOErrorbytesflash.utils:ByteArrayThe ByteArray object to read data into. offsetuint0The offset into bytes at which data read should begin. Defaults to 0. lengthuint0The number of bytes to read. The default value of 0 will cause all available data to be read. Reads length bytes of data from the stream. The bytes are read into the ByteArray object specified by bytes, starting offset bytes into the ByteArray object. readDouble Reads an IEEE 754 double-precision floating-point number from the stream.There is insufficient data available to read. If a local SWF file triggers a security warning, Flash Player prevents the URLStream data from being available to ActionScript. When this happens, the bytesAvailable property returns 0 even if data has been received, and any of the read methods throws an EOFError exception. EOFErrorflash.errors:EOFErrorAn I/O error occurred on the stream, or the stream is not open. IOErrorflash.errors:IOErrorAn IEEE 754 double-precision floating-point number from the stream. Number Reads an IEEE 754 double-precision floating-point number from the stream. readFloat Reads an IEEE 754 single-precision floating-point number from the stream.There is insufficient data available to read. If a local SWF file triggers a security warning, Flash Player prevents the URLStream data from being available to ActionScript. When this happens, the bytesAvailable property returns 0 even if data has been received, and any of the read methods throws an EOFError exception. EOFErrorflash.errors:EOFErrorAn I/O error occurred on the stream, or the stream is not open. IOErrorflash.errors:IOErrorAn IEEE 754 single-precision floating-point number from the stream. Number Reads an IEEE 754 single-precision floating-point number from the stream. readInt Reads a signed 32-bit integer from the stream.There is insufficient data available to read. If a local SWF file triggers a security warning, Flash Player prevents the URLStream data from being available to ActionScript. When this happens, the bytesAvailable property returns 0 even if data has been received, and any of the read methods throws an EOFError exception. EOFErrorflash.errors:EOFErrorAn I/O error occurred on the stream, or the stream is not open. IOErrorflash.errors:IOErrorValue in the range -2147483648...2147483647. int Reads a signed 32-bit integer from the stream.

The returned value is in the range -2147483648...2147483647.

readMultiByte Reads a multibyte string of specified length from the byte stream using the specified character set.There is insufficient data available to read. If a local SWF file triggers a security warning, Flash Player prevents the URLStream data from being available to ActionScript. When this happens, the bytesAvailable property returns 0 even if data has been received, and any of the read methods throws an EOFError exception. EOFErrorflash.errors:EOFErrorUTF-8 encoded string. StringlengthuintThe number of bytes from the byte stream to read. charSetStringThe string denoting the character set to use to interpret the bytes. Possible character set strings include "shift_jis", "CN-GB", "iso-8859-1", and others. For a complete list, see Supported Character Sets.

Note: If the value for the charSet parameter is not recognized by the current system, the application uses the system's default code page as the character set. For example, a value for the charSet parameter, as in myTest.readMultiByte(22, "iso-8859-01") that uses 01 instead of 1 might work on your development machine, but not on another machine. On the other machine, the application will use the system's default code page.

Reads a multibyte string of specified length from the byte stream using the specified character set.
readObject Reads an object from the socket, encoded in Action Message Format (AMF).There is insufficient data available to read. If a local SWF file triggers a security warning, Flash Player prevents the URLStream data from being available to ActionScript. When this happens, the bytesAvailable property returns 0 even if data has been received, and any of the read methods throws an EOFError exception. EOFErrorflash.errors:EOFErrorAn I/O error occurred on the stream, or the stream is not open. IOErrorflash.errors:IOErrorThe deserialized object. Reads an object from the socket, encoded in Action Message Format (AMF). ObjectEncodingreadShort Reads a signed 16-bit integer from the stream.There is insufficient data available to read. If a local SWF file triggers a security warning, Flash Player prevents the URLStream data from being available to ActionScript. When this happens, the bytesAvailable property returns 0 even if data has been received, and any of the read methods throws an EOFError exception. EOFErrorflash.errors:EOFErrorAn I/O error occurred on the stream, or the stream is not open. IOErrorflash.errors:IOErrorValue in the range -32768...32767. int Reads a signed 16-bit integer from the stream.

The returned value is in the range -32768...32767.

readUTFBytes Reads a sequence of length UTF-8 bytes from the stream, and returns a string.There is insufficient data available to read. If a local SWF file triggers a security warning, Flash Player prevents the URLStream data from being available to ActionScript. When this happens, the bytesAvailable property returns 0 even if data has been received, and any of the read methods throws an EOFError exception. EOFErrorflash.errors:EOFErrorAn I/O error occurred on the stream, or the stream is not open. IOErrorflash.errors:IOErrorA UTF-8 string produced by the byte representation of characters of specified length. StringlengthuintA sequence of UTF-8 bytes. Reads a sequence of length UTF-8 bytes from the stream, and returns a string. readUTF Reads a UTF-8 string from the stream.There is insufficient data available to read. If a local SWF file triggers a security warning, Flash Player prevents the URLStream data from being available to ActionScript. When this happens, the bytesAvailable property returns 0 even if data has been received, and any of the read methods throws an EOFError exception. EOFErrorflash.errors:EOFErrorAn I/O error occurred on the stream, or the stream is not open. IOErrorflash.errors:IOErrorA UTF-8 string. String Reads a UTF-8 string from the stream. The string is assumed to be prefixed with an unsigned short indicating the length in bytes. readUnsignedByte Reads an unsigned byte from the stream.There is insufficient data available to read. If a local SWF file triggers a security warning, Flash Player prevents the URLStream data from being available to ActionScript. When this happens, the bytesAvailable property returns 0 even if data has been received, and any of the read methods throws an EOFError exception. EOFErrorflash.errors:EOFErrorAn I/O error occurred on the stream, or the stream is not open. IOErrorflash.errors:IOErrorValue in the range 0...255. uint Reads an unsigned byte from the stream.

The returned value is in the range 0...255.

readUnsignedInt Reads an unsigned 32-bit integer from the stream.There is insufficient data available to read. If a local SWF file triggers a security warning, Flash Player prevents the URLStream data from being available to ActionScript. When this happens, the bytesAvailable property returns 0 even if data has been received, and any of the read methods throws an EOFError exception. EOFErrorflash.errors:EOFErrorAn I/O error occurred on the stream, or the stream is not open. IOErrorflash.errors:IOErrorValue in the range 0...4294967295. uint Reads an unsigned 32-bit integer from the stream.

The returned value is in the range 0...4294967295.

readUnsignedShort Reads an unsigned 16-bit integer from the stream.There is insufficient data available to read. If a local SWF file triggers a security warning, Flash Player prevents the URLStream data from being available to ActionScript. When this happens, the bytesAvailable property returns 0 even if data has been received, and any of the read methods throws an EOFError exception. EOFErrorflash.errors:EOFErrorAn I/O error occurred on the stream, or the stream is not open. IOErrorflash.errors:IOErrorValue in the range 0...65535. uint Reads an unsigned 16-bit integer from the stream.

The returned value is in the range 0...65535.

bytesAvailable Returns the number of bytes of data available for reading in the input buffer.uint Returns the number of bytes of data available for reading in the input buffer. Your code must call the bytesAvailable property to ensure that sufficient data is available before you try to read it with one of the read methods. connected Indicates whether this URLStream object is currently connected.Boolean Indicates whether this URLStream object is currently connected. A call to this property returns a value of true if the URLStream object is connected, or false otherwise. endian Indicates the byte order for the data.StringEndian.BIG_ENDIAN Indicates the byte order for the data. Possible values are Endian.BIG_ENDIAN or Endian.LITTLE_ENDIAN. flash.utils.EndianobjectEncoding Controls the version of Action Message Format (AMF) used when writing or reading an object.uint Controls the version of Action Message Format (AMF) used when writing or reading an object. readObject()ObjectEncoding class
NetGroupSendMode The NetGroupSendMode class is an enumeration of constant values used for the sendMode parameter of the NetGroup.sendToNeighbor() method.An enumeration of constant values used for the sendMode parameter of the sendToNeighbor() method in the NetGroup class. method of the NetGroup class Object The NetGroupSendMode class is an enumeration of constant values used for the sendMode parameter of the NetGroup.sendToNeighbor() method. flash.net.NetGroup.sendToNeighbor()NEXT_DECREASING Specifies the neighbor with the nearest group address in the decreasing direction.nextDecreasingString Specifies the neighbor with the nearest group address in the decreasing direction. NEXT_INCREASING Specifies the neighbor with the nearest group address in the increasing direction.nextIncreasingString Specifies the neighbor with the nearest group address in the increasing direction. SharedObject The SharedObject class is used to read and store limited amounts of data on a user's computer or on a server.flash.events:EventDispatcher The SharedObject class is used to read and store limited amounts of data on a user's computer or on a server. Shared objects offer real-time data sharing between multiple client SWF files and objects that are persistent on the local computer or remote server. Local shared objects are similar to browser cookies and remote shared objects are similar to real-time data transfer devices. To use remote shared objects, you need Adobe Flash Media Server.

Use shared objects to do the following:

  • Maintain local persistence. This is the simplest way to use a shared object, and does not require Flash Media Server. For example, you can call SharedObject.getLocal() to create a shared object in an application, such as a calculator with memory. When the user closes the calculator, Flash Player saves the last value in a shared object on the user's computer. The next time the calculator is run, it contains the values it had previously. Alternatively, if you set the shared object's properties to null before the calculator application is closed, the next time the application runs, it opens without any values. Another example of maintaining local persistence is tracking user preferences or other data for a complex website, such as a record of which articles a user read on a news site. Tracking this information allows you to display articles that have already been read differently from new, unread articles. Storing this information on the user's computer reduces server load.
  • Store and share data on Flash Media Server. A shared object can store data on the server for other clients to retrieve. For example, call SharedObject.getRemote() to create a remote shared object, such as a phone list, that is persistent on the server. Whenever a client makes changes to the shared object, the revised data is available to all clients currently connected to the object or who later connect to it. If the object is also persistent locally, and a client changes data while not connected to the server, the data is copied to the remote shared object the next time the client connects to the object.
  • Share data in real time. A shared object can share data among multiple clients in real time. For example, you can open a remote shared object that stores a list of users connected to a chat room that is visible to all clients connected to the object. When a user enters or leaves the chat room, the object is updated and all clients that are connected to the object see the revised list of chat room users.

To create a local shared object, call SharedObject.getLocal(). To create a remote shared object, call SharedObject.getRemote().

When an application closes, shared objects are flushed, or written to a disk. You can also call the flush() method to explicitly write data to a disk.

Local disk space considerations. Local shared objects have some limitations that are important to consider as you design your application. Sometimes SWF files may not be allowed to write local shared objects, and sometimes the data stored in local shared objects can be deleted without your knowledge. Flash Player users can manage the disk space that is available to individual domains or to all domains. When users decrease the amount of disk space available, some local shared objects may be deleted. Flash Player users also have privacy controls that can prevent third-party domains (domains other than the domain in the current browser address bar) from reading or writing local shared objects.

Note: SWF files that are stored and run on a local computer, not from a remote server, can always write third-party shared objects to disk. For more information about third-party shared objects, see the Global Storage Settings panel in Flash Player Help.

It's a good idea to check for failures related to the amount of disk space and to user privacy controls. Perform these checks when you call getLocal() and flush():

  • SharedObject.getLocal() — Flash Player throws an exception when a call to this method fails, such as when the user has disabled third-party shared objects and the domain of your SWF file does not match the domain in the browser address bar.
  • SharedObject.flush() — Flash Player throws an exception when a call to this method fails. It returns SharedObjectFlushStatus.FLUSHED when it succeeds. It returns SharedObjectFlushStatus.PENDING when additional storage space is needed. Flash Player prompts the user to allow an increase in storage space for locally saved information. Thereafter, the netStatus event is dispatched with an information object indicating whether the flush failed or succeeded.

If your SWF file attempts to create or modify local shared objects, make sure that your SWF file is at least 215 pixels wide and at least 138 pixels high (the minimum dimensions for displaying the dialog box that prompts users to increase their local shared object storage limit). If your SWF file is smaller than these dimensions and an increase in the storage limit is required, SharedObject.flush() fails, returning SharedObjectFlushedStatus.PENDING and dispatching the netStatus event.

Remote shared objects. With Flash Media Server, you can create and use remote shared objects, that are shared in real-time by all clients connected to your application. When one client changes a property of a remote shared object, the property is changed for all connected clients. You can use remote shared objects to synchronize clients, for example, users in a multi-player game.

Each remote shared object has a data property which is an Object with properties that store data. Call setProperty() to change an property of the data object. The server updates the properties, dispatches a sync event, and sends the properties back to the connected clients.

You can choose to make remote shared objects persistent on the client, the server, or both. By default, Flash Player saves locally persistent remote shared objects up to 100K in size. When you try to save a larger object, Flash Player displays the Local Storage dialog box, which lets the user allow or deny local storage for the shared object. Make sure your Stage size is at least 215 by 138 pixels; this is the minimum size Flash requires to display the dialog box.

If the user selects Allow, the server saves the shared object and dispatches a netStatus event with a code property of SharedObject.Flush.Success. If the user select Deny, the server does not save the shared object and dispatches a netStatus event with a code property of SharedObject.Flush.Failed.

The following code creates (and on subsequent executions, retrieves) a shared object object using the ID "application-name". When the Save button is clicked, the saveValue() method attempts to save a property named savedValue to the data property of the SharedObject object. If Flash Player must ask for permission to save the data, when the user grants or denies permission the onFlushStatus() method is called. When the Clear button is clicked, the clearValue() method deletes the value saved in savedValue; the next time the SWF file is loaded, the value that is retrieved is undefined. package { import flash.display.Sprite; import flash.events.MouseEvent; import flash.events.NetStatusEvent; import flash.net.SharedObject; import flash.net.SharedObjectFlushStatus; import flash.text.TextField; import flash.text.TextFieldAutoSize; import flash.text.TextFieldType; public class SharedObjectExample extends Sprite { private var mySo:SharedObject; public function SharedObjectExample() { buildUI(); saveBtn.addEventListener(MouseEvent.CLICK, saveValue); clearBtn.addEventListener(MouseEvent.CLICK, clearValue); mySo = SharedObject.getLocal("application-name"); output.appendText("SharedObject loaded...\n"); output.appendText("loaded value: " + mySo.data.savedValue + "\n\n"); } private function saveValue(event:MouseEvent):void { output.appendText("saving value...\n"); mySo.data.savedValue = input.text; var flushStatus:String = null; try { flushStatus = mySo.flush(10000); } catch (error:Error) { output.appendText("Error...Could not write SharedObject to disk\n"); } if (flushStatus != null) { switch (flushStatus) { case SharedObjectFlushStatus.PENDING: output.appendText("Requesting permission to save object...\n"); mySo.addEventListener(NetStatusEvent.NET_STATUS, onFlushStatus); break; case SharedObjectFlushStatus.FLUSHED: output.appendText("Value flushed to disk.\n"); break; } } output.appendText("\n"); } private function clearValue(event:MouseEvent):void { output.appendText("Cleared saved value...Reload SWF and the value should be \"undefined\".\n\n"); delete mySo.data.savedValue; } private function onFlushStatus(event:NetStatusEvent):void { output.appendText("User closed permission dialog...\n"); switch (event.info.code) { case "SharedObject.Flush.Success": output.appendText("User granted permission -- value saved.\n"); break; case "SharedObject.Flush.Failed": output.appendText("User denied permission -- value not saved.\n"); break; } output.appendText("\n"); mySo.removeEventListener(NetStatusEvent.NET_STATUS, onFlushStatus); } // UI elements private var inputLbl:TextField; private var input:TextField; private var output:TextField; private var saveBtn:Sprite; private var clearBtn:Sprite; private function buildUI():void { // input label inputLbl = new TextField(); addChild(inputLbl); inputLbl.x = 10; inputLbl.y = 10; inputLbl.text = "Value to save:"; // input TextField input = new TextField(); addChild(input); input.x = 80; input.y = 10; input.width = 100; input.height = 20; input.border = true; input.background = true; input.type = TextFieldType.INPUT; // output TextField output = new TextField(); addChild(output); output.x = 10; output.y = 35; output.width = 250; output.height = 250; output.multiline = true; output.wordWrap = true; output.border = true; output.background = true; // Save button saveBtn = new Sprite(); addChild(saveBtn); saveBtn.x = 190; saveBtn.y = 10; saveBtn.useHandCursor = true; saveBtn.graphics.lineStyle(1); saveBtn.graphics.beginFill(0xcccccc); saveBtn.graphics.drawRoundRect(0, 0, 30, 20, 5, 5); var saveLbl:TextField = new TextField(); saveBtn.addChild(saveLbl); saveLbl.text = "Save"; saveLbl.selectable = false; // Clear button clearBtn = new Sprite(); addChild(clearBtn); clearBtn.x = 230; clearBtn.y = 10; clearBtn.useHandCursor = true; clearBtn.graphics.lineStyle(1); clearBtn.graphics.beginFill(0xcccccc); clearBtn.graphics.drawRoundRect(0, 0, 30, 20, 5, 5); var clearLbl:TextField = new TextField(); clearBtn.addChild(clearLbl); clearLbl.text = "Clear"; clearLbl.selectable = false; } } }
flush()getLocal()netStatussync Dispatched when a remote shared object has been updated by the server.flash.events.SyncEvent.SYNCflash.events.SyncEvent Dispatched when a remote shared object has been updated by the server. getRemote()netStatus Dispatched when a SharedObject instance is reporting its status or error condition.flash.events.NetStatusEvent.NET_STATUSflash.events.NetStatusEvent Dispatched when a SharedObject instance 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 whether the shared object was successfully written to the local disk. flash.events.NetStatusEvent.infoasyncError Dispatched when an exception is thrown asynchronously &#x2014; that is, from native asynchronous code.flash.events.AsyncErrorEvent.ASYNC_ERRORflash.events.AsyncErrorEvent Dispatched when an exception is thrown asynchronously — that is, from native asynchronous code. clear For local shared objects, purges all of the data and deletes the shared object from the disk. For local shared objects, purges all of the data and deletes the shared object from the disk. The reference to the shared object is still active, but its data properties are deleted.

For remote shared objects used with Flash Media Server, clear() disconnects the object and purges all of the data. If the shared object is locally persistent, this method also deletes the shared object from the disk. The reference to the shared object is still active, but its data properties are deleted.

The following code creates (and on subsequent executions, retrieves) a SharedObject object using an id with the value of hostName. A property named username is added to the data property of the SharedObject object. The clear() method is finally called, which wipes out all information that was added to the data object (in this case was a single property named username). package { import flash.net.SharedObject; public class SharedObject_clear { private var hostName:String = "yourDomain"; private var username:String = "yourUsername"; public function SharedObject_clear() { var mySo:SharedObject = SharedObject.getLocal(hostName); if(mySo.data.username == null) { mySo.data.username = username; trace("set: " + mySo.data.username); // yourUsername } else { mySo.clear(); trace("cleared: " + mySo.data.username); // undefined } } } }
close Closes the connection between a remote shared object and the server. Closes the connection between a remote shared object and the server. If a remote shared object is locally persistent, the user can make changes to the local copy of the object after this method is called. Any changes made to the local object are sent to the server the next time the user connects to the remote shared object. connect Connects to a remote shared object on a server through a specified NetConnection object.Flash Player could not connect to the specified remote shared object. Verify that the NetConnection instance is valid and connected and that the remote shared object was successfully created on the server. ErrorErrormyConnectionflash.net:NetConnectionA NetConnection object that uses the Real-Time Messaging Protocol (RTMP), such as a NetConnection object used to communicate with Flash Media Server. paramsStringnullA string defining a message to pass to the remote shared object on the server. Cannot be used with Flash Media Server. Connects to a remote shared object on a server through a specified NetConnection object. Use this method after calling getRemote(). When a connection is successful, the sync event is dispatched.

Before attempting to work with a remote shared object, first check for any errors using a try..catch..finally statement. Then, listen for and handle the sync event before you make changes to the shared object. Any changes made locally — before the sync event is dispatched — might be lost.

Call the connect() method to connect to a remote shared object, for example:

var myRemoteSO:SharedObject = SharedObject.getRemote("mo", myNC.uri, false); myRemoteSO.connect(myNC);
getRemote()synctry..catch..finallyNetConnection
flush Immediately writes a locally persistent shared object to a local file.Flash Player cannot write the shared object to disk. This error might occur if the user has permanently disallowed local information storage for objects from this domain.

Note: Local content can always write shared objects from third-party domains (domains other than the domain in the current browser address bar) to disk, even if writing of third-party shared objects to disk is disallowed.

ErrorError
Either of the following values:
  • SharedObjectFlushStatus.PENDING: The user has permitted local information storage for objects from this domain, but the amount of space allotted is not sufficient to store the object. Flash Player prompts the user to allow more space. To allow space for the shared object to grow when it is saved, thus avoiding a SharedObjectFlushStatus.PENDING return value, pass a value for minDiskSpace.
  • SharedObjectFlushStatus.FLUSHED: The shared object has been successfully written to a file on the local disk.
String
minDiskSpaceint0The minimum disk space, in bytes, that must be allotted for this object.
Immediately writes a locally persistent shared object to a local file. If you don't use this method, Flash Player writes the shared object to a file when the shared object session ends — that is, when the SWF file is closed, when the shared object is garbage-collected because it no longer has any references to it, or when you call SharedObject.clear() or SharedObject.close().

If this method returns SharedObjectFlushStatus.PENDING, Flash Player displays a dialog box asking the user to increase the amount of disk space available to objects from this domain. To allow space for the shared object to grow when it is saved in the future, which avoids return values of PENDING, pass a value for minDiskSpace. When Flash Player tries to write the file, it looks for the number of bytes passed to minDiskSpace, instead of looking for enough space to save the shared object at its current size.

For example, if you expect a shared object to grow to a maximum size of 500 bytes, even though it might start out much smaller, pass 500 for minDiskSpace. If Flash asks the user to allot disk space for the shared object, it asks for 500 bytes. After the user allots the requested amount of space, Flash won't have to ask for more space on future attempts to flush the object (as long as its size doesn't exceed 500 bytes).

After the user responds to the dialog box, this method is called again. A netStatus event is dispatched with a code property of SharedObject.Flush.Success or SharedObject.Flush.Failed.

The following code creates (and on subsequent executions, retrieves) a SharedObject object using an id with the value of hostName. A property named username is added to the data property of the SharedObject object. The flush() method is then called, followed by a check to see if the string pending, or a boolean value of true or false was returned. One should be aware that all open SharedObject instances will automatically be flushed whenever the current instance of the Flash Player is closed. package { import flash.net.SharedObject; public class SharedObject_flush { private var hostName:String = "yourDomain"; private var username:String = "yourUsername"; public function SharedObject_flush() { var mySo:SharedObject = SharedObject.getLocal(hostName); mySo.data.username = username; var flushResult:Object = mySo.flush(); trace("flushResult: " + flushResult); trace(mySo.data.username); // yourUsername } } }
clear()
getLocal Returns a reference to a locally persistent shared object that is only available to the current client.Flash Player cannot create the shared object for whatever reason. This error might occur is if persistent shared object creation and storage by third-party Flash content is prohibited (does not apply to local content). Users can prohibit third-party persistent shared objects on the Global Storage Settings panel of the Settings Manager, located at http://www.adobe.com/support/documentation/en/flashplayer/help/settings_manager03.html. ErrorErrorA reference to a shared object that is persistent locally and is available only to the current client. If Flash Player can't create or find the shared object (for example, if localPath was specified but no such directory exists), this method throws an exception. flash.net:SharedObjectnameStringThe name of the object. The name can include forward slashes (/); for example, work/addresses is a legal name. Spaces are not allowed in a shared object name, nor are the following characters:
  ~ % & \ ; : " ' , < > ? # 
  
localPathStringnullThe full or partial path to the SWF file that created the shared object, and that determines where the shared object will be stored locally. If you do not specify this parameter, the full path is used. secureBooleanfalseDetermines whether access to this shared object is restricted to SWF files that are delivered over an HTTPS connection. If your SWF file is delivered over HTTPS, this parameter's value has the following effects:
  • If this parameter is set to true, Flash Player creates a new secure shared object or gets a reference to an existing secure shared object. This secure shared object can be read from or written to only by SWF files delivered over HTTPS that call SharedObject.getLocal() with the secure parameter set to true.
  • If this parameter is set to false, Flash Player creates a new shared object or gets a reference to an existing shared object that can be read from or written to by SWF files delivered over non-HTTPS connections.

If your SWF file is delivered over a non-HTTPS connection and you try to set this parameter to true, the creation of a new shared object (or the access of a previously created secure shared object) fails and null is returned. Regardless of the value of this parameter, the created shared objects count toward the total amount of disk space allowed for a domain.

The following diagram shows the use of the secure parameter:

Returns a reference to a locally persistent shared object that is only available to the current client. If the shared object does not already exist, this method creates one. If any values passed to getLocal() are invalid or if the call fails, Flash Player throws an exception.

The following code shows how you assign the returned shared object reference to a variable:

var so:SharedObject = SharedObject.getLocal("savedData");

Note: If the user has chosen to never allow local storage for this domain, the object is not saved locally, even if a value for localPath is specified. The exception to this rule is local content. Local content can always write shared objects from third-party domains (domains other than the domain in the current browser address bar) to disk, even if writing of third-party shared objects to disk is disallowed.

To avoid name conflicts, Flash looks at the location of the SWF file creating the shared object. For example, if a SWF file at www.myCompany.com/apps/stockwatcher.swf creates a shared object named portfolio, that shared object does not conflict with another object named portfolio that was created by a SWF file at www.yourCompany.com/photoshoot.swf because the SWF files originate from different directories.

Although the localPath parameter is optional, you should give some thought to its use, especially if other SWF files need to access the shared object. If the data in the shared object is specific to one SWF file that will not be moved to another location, then use of the default value makes sense. If other SWF files need access to the shared object, or if the SWF file that creates the shared object will later be moved, then the value of this parameter affects how accessible the shared object will be. For example, if you create a shared object with localPath set to the default value of the full path to the SWF file, no other SWF file can access that shared object. If you later move the original SWF file to another location, not even that SWF file can access the data already stored in the shared object.

To avoid inadvertently restricting access to a shared object, use the localpath parameter. The most permissive approach is to set localPath to / (slash), which makes the shared object available to all SWF files in the domain, but increases the likelihood of name conflicts with other shared objects in the domain. A more restrictive approach is to append localPath with folder names that are in the full path to the SWF file. For example, for a portfolio shared object created by the SWF file at www.myCompany.com/apps/stockwatcher.swf, you could set the localPath parameter to /, /apps, or /apps/stockwatcher.swf. You must determine which approach provides optimal flexibility for your application.

When using this method, consider the following security model:

  • You cannot access shared objects across sandbox boundaries.
  • Users can restrict shared object access by using the Flash Player Settings dialog box or the Settings Manager. By default, an application can create shared objects of up 100 KB of data per domain. Administrators and users can also place restrictions on the ability to write to the file system.

Suppose you publish SWF file content to be played back as local files (either locally installed SWF files or EXE files), and you need to access a specific shared object from more than one local SWF file. In this situation, be aware that for local files, two different locations might be used to store shared objects. The domain that is used depends on the security permissions granted to the local file that created the shared object. Local files can have three different levels of permissions:

  1. Access to the local filesystem only.
  2. Access to the network only.
  3. Access to both the network and the local filesystem.

Local files with access to the local filesystem (level 1 or 3) store their shared objects in one location. Local files without access to the local filesystem (level 2) store their shared objects in another location.

You can prevent a SWF file from using this method by setting the allowNetworking parameter of the the object and embed tags in the HTML page that contains the SWF content.

For more information, see the Flash Player Developer Center Topic: Security.

getRemote Returns a reference to a shared object on Flash Media Server that multiple clients can access.Flash Player can't create or find the shared object. This might occur if nonexistent paths were specified for the remotePath and persistence parameters. ErrorErrorA reference to an object that can be shared across multiple clients. flash.net:SharedObjectnameStringThe name of the remote shared object. The name can include forward slashes (/); for example, work/addresses is a legal name. Spaces are not allowed in a shared object name, nor are the following characters:
    ~ % & \ ; :  " ' , > ? ? #
remotePathStringnullThe URI of the server on which the shared object will be stored. This URI must be identical to the URI of the NetConnection object passed to the connect() method. persistenceObjectfalseSpecifies whether the attributes of the shared object's data property are persistent locally, remotely, or both. This parameter can also specify where the shared object will be stored locally. Acceptable values are as follows:
  • A value of false specifies that the shared object is not persistent on the client or server.
  • A value of true specifies that the shared object is persistent only on the server.
  • A full or partial local path to the shared object indicates that the shared object is persistent on the client and the server. On the client, it is stored in the specified path; on the server, it is stored in a subdirectory within the application directory.

Note: If the user has chosen to never allow local storage for this domain, the object will not be saved locally, even if a local path is specified for persistence. For more information, see the class description.

secureBooleanfalseDetermines whether access to this shared object is restricted to SWF files that are delivered over an HTTPS connection. For more information, see the description of the secure parameter in the getLocal method entry.
Returns a reference to a shared object on Flash Media Server that multiple clients can access. If the remote shared object does not already exist, this method creates one.

To create a remote shared object, call getRemote() the call connect() to connect the remote shared object to the server, as in the following:

var nc:NetConnection = new NetConnection(); nc.connect("rtmp://somedomain.com/applicationName"); var myRemoteSO:SharedObject = SharedObject.getRemote("mo", nc.uri, false); myRemoteSO.connect(nc);

To confirm that the local and remote copies of the shared object are synchronized, listen for and handle the sync event. All clients that want to share this object must pass the same values for the name and remotePath parameters.

To create a shared object that is available only to the current client, use SharedObject.getLocal().

connect()getLocal()
send Broadcasts a message to all clients connected to a remote shared object, including the client that sent the message.argumentsOne or more arguments: A string that identifies the message, the name of one or more handler functions to attach to the shared object, and optional parameters of any type. The handler name can be only one level deep (that is, it can't be of the form parent/child) and is relative to the shared object. The arguments are serialized and sent over the connection, and the receiving handler receives them in the same order. If a parameter is a circular object (for example, a linked list that is circular), the serializer handles the references correctly.

Note: Do not use a reserved term for the function names. For example, myRemoteSO.send("close") will fail.

Broadcasts a message to all clients connected to a remote shared object, including the client that sent the message. To process and respond to the message, create a callback function attached to the shared object.
setDirty Indicates to the server that the value of a property in the shared object has changed.propertyNameStringThe name of the property that has changed. Indicates to the server that the value of a property in the shared object has changed. This method marks properties as dirty, which means changed.

Call the SharedObject.setProperty() to create properties for a shared object.

The SharedObject.setProperty() method implements setDirty(). In most cases, such as when the value of a property is a primitive type like String or Number, you can call setProperty() instead of calling setDirty(). However, when the value of a property is an object that contains its own properties, call setDirty() to indicate when a value within the object has changed.

SharedObject.data (client-side property)setProperty()
setProperty Updates the value of a property in a shared object and indicates to the server that the value of the property has changed.propertyNameStringThe name of the property in the shared object. valueObjectnullThe value of the property (an ActionScript object), or null to delete the property. Updates the value of a property in a shared object and indicates to the server that the value of the property has changed. The setProperty() method explicitly marks properties as changed, or dirty.

For more information about remote shared objects see the Flash Media Server documentation.

Note: The SharedObject.setProperty() method implements the setDirty() method. In most cases, such as when the value of a property is a primitive type like String or Number, you would use setProperty() instead of setDirty. However, when the value of a property is an object that contains its own properties, use setDirty() to indicate when a value within the object has changed. In general, it is a good idea to call setProperty() rather than setDirty(), because setProperty() updates a property value only when that value has changed, whereas setDirty() forces synchronization on all subscribed clients.

SharedObject.data (client-side property)
client Indicates the object on which callback methods are invoked.ObjectThe client property must be set to a non-null object. TypeErrorTypeError Indicates the object on which callback methods are invoked. The default object is this. You can set the client property to another object, and callback methods will be invoked on that other object. data The collection of attributes assigned to the data property of the object; these attributes can be shared and stored.Object The collection of attributes assigned to the data property of the object; these attributes can be shared and stored. Each attribute can be an object of any ActionScript or JavaScript type — Array, Number, Boolean, ByteArray, XML, and so on. For example, the following lines assign values to various aspects of a shared object: var items_array:Array = new Array(101, 346, 483); var currentUserIsAdmin:Boolean = true; var currentUserName:String = "Ramona"; var my_so:SharedObject = SharedObject.getLocal("superfoo"); my_so.data.itemNumbers = items_array; my_so.data.adminPrivileges = currentUserIsAdmin; my_so.data.userName = currentUserName; for (var prop in my_so.data) { trace(prop+": "+my_so.data[prop]); }

All attributes of a shared object's data property are saved if the object is persistent, and the shared object contains the following information:

userName: Ramona adminPrivileges: true itemNumbers: 101,346,483

Note: Do not assign values directly to the data property of a shared object, as in so.data = someValue; Flash Player ignores these assignments.

To delete attributes for local shared objects, use code such as delete so.data.attributeName; setting an attribute to null or undefined for a local shared object does not delete the attribute.

To create private values for a shared object — values that are available only to the client instance while the object is in use and are not stored with the object when it is closed — create properties that are not named data to store them, as shown in the following example:

var my_so:SharedObject = SharedObject.getLocal("superfoo"); my_so.favoriteColor = "blue"; my_so.favoriteNightClub = "The Bluenote Tavern"; my_so.favoriteSong = "My World is Blue"; for (var prop in my_so) { trace(prop+": "+my_so[prop]); }

The shared object contains the following data:

favoriteSong: My World is Blue favoriteNightClub: The Bluenote Tavern favoriteColor: blue data: [object Object]

For remote shared objects used with a server, all attributes of the data property are available to all clients connected to the shared object, and all attributes are saved if the object is persistent. If one client changes the value of an attribute, all clients now see the new value.

getLocal()
defaultObjectEncoding The default object encoding (AMF version) for all local shared objects created in the SWF file.uint The default object encoding (AMF version) for all local shared objects created in the SWF file. When local shared objects are written to disk, the SharedObject.defaultObjectEncoding property indicates which Action Message Format version should be used: the ActionScript 3.0 format (AMF3) or the ActionScript 1.0 or 2.0 format (AMF0).

For more information about object encoding, including the difference between encoding in local and remote shared objects, see the description of the objectEncoding property.

The default value of SharedObject.defaultObjectEncoding is set to use the ActionScript 3.0 format, AMF3. If you need to write local shared objects that ActionScript 2.0 or 1.0 SWF files can read, set SharedObject.defaultObjectEncoding to use the ActionScript 1.0 or ActionScript 2.0 format, flash.net.ObjectEncoding.AMF0, at the beginning of your script, before you create any local shared objects. All local shared objects created thereafter will use AMF0 encoding and can interact with older content. You cannot change the objectEncoding value of existing local shared objects by setting SharedObject.defaultObjectEncoding after the local shared objects have been created.

To set the object encoding on a per-object basis, rather than for all shared objects created by the SWF file, set the objectEncoding property of the local shared object instead.

objectEncoding propertyObjectEncoding class
objectEncoding The object encoding (AMF version) for this shared object.uintYou attempted to set the value of the objectEncoding property on a remote shared object. This property is read-only for remote shared objects because its value is determined by the associated NetConnection instance. ReferenceErrorReferenceError The object encoding (AMF version) for this shared object. When a local shared object is written to disk, the objectEncoding property indicates which Action Message Format version should be used: the ActionScript 3.0 format (AMF3) or the ActionScript 1.0 or 2.0 format (AMF0).

Object encoding is handled differently depending if the shared object is local or remote.

  • Local shared objects. You can get or set the value of the objectEncoding property for local shared objects. The value of objectEncoding affects what formatting is used for writing this local shared object. If this local shared object must be readable by ActionScript 2.0 or 1.0 SWF files, set objectEncoding to ObjectEncoding.AMF0. Even if object encoding is set to write AMF3, Flash Player can still read AMF0 local shared objects. That is, if you use the default value of this property, ObjectEncoding.AMF3, your SWF file can still read shared objects created by ActionScript 2.0 or 1.0 SWF files.
  • Remote shared objects. When connected to the server, a remote shared object inherits its objectEncoding setting from the associated NetConnection instance (the instance used to connect to the remote shared object). When not connected to the server, a remote shared object inherits the defaultObjectEncoding setting from the associated NetConnection instance. Because the value of a remote shared object's objectEncoding property is determined by the NetConnection instance, this property is read-only for remote shared objects.
defaultObjectEncodingflash.net.ObjectEncoding
size The current size of the shared object, in bytes.uint The current size of the shared object, in bytes.

Flash calculates the size of a shared object by stepping through all of its data properties; the more data properties the object has, the longer it takes to estimate its size. Estimating object size can take significant processing time, so you may want to avoid using this method unless you have a specific need for it.

The following code creates a SharedObject object using an id "thehobbit". A property named username is added to the data property of the SharedObject object. The size property is then traced, which returns the value indicated. import flash.net.SharedObject; // if these get copied or not var mySo:SharedObject = SharedObject.getLocal("thehobbit"); mySo.data.username = "bilbobaggins"; trace(mySo.size); // 55
fps Specifies the number of times per second that a client's changes to a shared object are sent to the server.Number Specifies the number of times per second that a client's changes to a shared object are sent to the server.

Use this method when you want to control the amount of traffic between the client and the server. For example, if the connection between the client and server is relatively slow, you may want to set fps to a relatively low value. Conversely, if the client is connected to a multiuser application in which timing is important, you may want to set fps to a relatively high value.

Setting fps will trigger a sync event and update all changes to the server. If you only want to update the server manually, set fps to 0.

Changes are not sent to the server until the sync event has been dispatched. That is, if the response time from the server is slow, updates may be sent to the server less frequently than the value specified in this property.

NetGroupInfo The NetGroupInfo class specifies various Quality of Service (QoS) statistics related to a NetGroup object's underlying RTMFP Peer-to-Peer data transport.Object The NetGroupInfo class specifies various Quality of Service (QoS) statistics related to a NetGroup object's underlying RTMFP Peer-to-Peer data transport. The NetGroup.info property returns a NetGroupInfo object which is a snapshot of the current QoS state. flash.net.NetGroup.infoflash.net.NetGroup.post()flash.net.NetGroup.sendToNearest()flash.net.NetGroup.sendToNeighbor()flash.net.NetGroup.sendToAllNeighbors()flash.net.NetGroup.addWantObjects()flash.net.NetGroup.writeRequestedObject()toString Returns a string containing the values of the properties of the NetGroupInfo object.A string containing the values of the properties of the NetGroupInfo object StringReturns a text value listing the properties of this NetGroupInfo object. Returns a string containing the values of the properties of the NetGroupInfo object. objectReplicationReceiveBytesPerSecond Specifies the rate at which the local node is receiving objects from peers via the Object Replication system, in bytes per second.Number Specifies the rate at which the local node is receiving objects from peers via the Object Replication system, in bytes per second. flash.net.NetGroup.writeRequestedObject()objectReplicationSendBytesPerSecond Specifies the rate at which objects are being copied from the local node to peers by the Object Replication system, in bytes per second.Number Specifies the rate at which objects are being copied from the local node to peers by the Object Replication system, in bytes per second. flash.net.NetGroup.writeRequestedObject()postingReceiveControlBytesPerSecond Specifies the rate at which the local node is receiving posting control overhead messages from peers, in bytes per second.Number Specifies the rate at which the local node is receiving posting control overhead messages from peers, in bytes per second. flash.net.NetGroup.post()postingReceiveDataBytesPerSecond Specifies the rate at which the local node is receiving posting data from peers, in bytes per second.Number Specifies the rate at which the local node is receiving posting data from peers, in bytes per second. flash.net.NetGroup.post()postingSendControlBytesPerSecond Specifies the rate at which the local node is sending posting control overhead messages to peers, in bytes per second.Number Specifies the rate at which the local node is sending posting control overhead messages to peers, in bytes per second. flash.net.NetGroup.post()postingSendDataBytesPerSecond Specifies the rate at which the local node is sending posting data to peers, in bytes per second.Number Specifies the rate at which the local node is sending posting data to peers, in bytes per second. flash.net.NetGroup.post()routingReceiveBytesPerSecond Specifies the rate at which the local node is receiving directed routing messages from peers, in bytes per second.Number Specifies the rate at which the local node is receiving directed routing messages from peers, in bytes per second. flash.net.NetGroup.sendToNearest()flash.net.NetGroup.sendToNeighbor()flash.net.NetGroup.sendToAllNeighbors()routingSendBytesPerSecond Specifies the rate at which the local node is sending directed routing messages to peers, in bytes per second.Number Specifies the rate at which the local node is sending directed routing messages to peers, in bytes per second. flash.net.NetGroup.sendToNearest()flash.net.NetGroup.sendToNeighbor()flash.net.NetGroup.sendToAllNeighbors()URLLoaderDataFormat The URLLoaderDataFormat class provides values that specify how downloaded data is received.Object The URLLoaderDataFormat class provides values that specify how downloaded data is received. The following example uses the URLLoaderDataFormatExample class to display data format and status information for a file loaded at runtime. This is accomplished using the following steps:
  1. The class constructor creates a URLLoader instance named loader and a URLRequest instance named request, which is the location and name of the file to be loaded.
  2. The loader object is passed to the configureListeners() method, which adds listeners for each of the supported URLLoader events:
    • completeHandler(): listens for the complete event, which is dispatched after TextFile.txt has successfully loaded.
    • openHandler(): listens for the open event, dispatched upon start of the download (to the player) of TextFile.txt.
    • progressHandler(): listens for the progress events, dispatched when data is received as the download operation progresses.
    • securityErrorHandler(): listens for securityError events, which would be dispatched if the text file was accessed with the wrong local playback security setting.
    • httpStatusHandler(): listens for httpStatusHandler events, which will not be dispatched in this case since TextFile.txt is local.
    • ioErrorHandler(): listens for ioError events, which would happen only if there were a serious problem with the file, such as if it were missing.
  3. The request object is then passed to the loader.load() method, which loads the text file into memory using a DisplayObject object.

Notes:

  • You will need to compile the SWF file with "Local playback security" set to "Access local files only".
  • This example requires that a file named TextFile.txt be placed in the same directory as your SWF file. If you would like to see this example identify binary or URL-encoded data files, you will need to provide the file in the proper data format and change TextFile.txt to the name and location of the new file.

package { import flash.display.Sprite; import flash.events.*; import flash.net.*; public class URLLoaderDataFormatExample extends Sprite { private var source:String = "TextFile.txt"; private var dataFormat:String = URLLoaderDataFormat.TEXT; public function URLLoaderDataFormatExample () { var loader:URLLoader = new URLLoader(); loader.dataFormat = dataFormat; configureListeners(loader); var request:URLRequest = new URLRequest(source); try { loader.load(request); } catch (error:Error) { trace("Error loading requested document: " + source); } } private function configureListeners(dispatcher:URLLoader):void { dispatcher.addEventListener(Event.COMPLETE, completeHandler); dispatcher.addEventListener(Event.OPEN, openHandler); dispatcher.addEventListener(ProgressEvent.PROGRESS, progressHandler); dispatcher.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler); dispatcher.addEventListener(HTTPStatusEvent.HTTP_STATUS, httpStatusHandler); dispatcher.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler); } private function completeHandler(event:Event):void { var loader:URLLoader = URLLoader(event.target); switch(loader.dataFormat) { case URLLoaderDataFormat.TEXT : trace("completeHandler (text): " + loader.data); break; case URLLoaderDataFormat.BINARY : trace("completeHandler (binary): " + loader.data); break; case URLLoaderDataFormat.VARIABLES : trace("completeHandler (variables): " + loader.data); break; } } private function httpStatusHandler(event:Event):void { trace("httpStatusHandler: " + event); } private function ioErrorHandler(event:IOErrorEvent):void { trace("ioErrorHandler: " + event); } private function openHandler(event:Event):void { trace("openHandler: " + event); } private function progressHandler(event:ProgressEvent):void { trace("progressHandler loaded:" + event.bytesLoaded + " total: " + event.bytesTotal); } private function securityErrorHandler(event:SecurityErrorEvent):void { trace("securityErrorHandler: " + event); } } }
BINARY Specifies that downloaded data is received as raw binary data.binaryString Specifies that downloaded data is received as raw binary data. TEXT Specifies that downloaded data is received as text.textString Specifies that downloaded data is received as text. VARIABLES Specifies that downloaded data is received as URL-encoded variables.variablesString Specifies that downloaded data is received as URL-encoded variables.
NetStreamPlayTransitions The NetStreamPlayTransitions class specifies the valid strings that you can use with the NetStreamPlayOptions.transition property.Object The NetStreamPlayTransitions class specifies the valid strings that you can use with the NetStreamPlayOptions.transition property. These strings control the behavior that is used to transition to a new stream or to play a stream, depending on the transition mode that is used. NetStreamPlayOptionsNetStream.play2()APPEND_AND_WAIT Builds a playlist without starting to play it from the first stream.appendAndWaitString Builds a playlist without starting to play it from the first stream.

The APPEND_AND_WAIT transition mode is used with the NetStream.play2() method to build a playlist without immediately starting to play it from the first stream. Use this mode to load each item in the playlist except the last one. When you load the last stream in the playlist, set the transition mode to RESUME. At this point, Flash Player begins to stream and play the playlist.

You can use this mode to build a playlist from scratch, or to rebuild a playlist after a lost connection is recovered. For a new playlist, when NetStream.play2() is called with RESUME, Flash Player begins streaming and playing from the first stream, or from the start position specified. To recover from a lost connection, when you call the NetStream.play2() method with RESUME, Flash Player determines where the stream was interrupted and instructs the server to start streaming from that location. The server in turn is able to determine which stream in the playlist corresponds to that location, and starts streaming from that location.

This transition mode is in contrast to the APPEND mode, where playback starts immediately with the first stream.

APPENDRESUMENetStream.play2()
APPEND Adds the stream to a playlist and begins playback with the first stream.appendString Adds the stream to a playlist and begins playback with the first stream. This mode does the same thing as the NetStream.play() method with the reset flag set to false.

In this mode, Flash Media Server queues up the stream specified in NetStreamPlayOptions.streamName at the end of the playlist and ignores the NetStreamPlayOptions.oldStreamName parameter.

APPEND_AND_WAITNetStream.play()NetStream.play2()NetStreamPlayOptions.oldStreamNameNetStreamPlayOptions.streamName
RESET Clears any previous play calls and plays the specified stream immediately.resetString Clears any previous play calls and plays the specified stream immediately. This mode does the same thing as the NetStream.play() method with the reset flag set to true (the default behavior for NetStream.play()).

In this mode, the currently playing stream is flushed and the stream specified in NetStreamPlayOptions.streamName starts to play. The NetStreamPlayOptions.oldStreamName parameter is ignored.

NetStream.play()NetStream.play2()NetStreamPlayOptions.oldStreamNameNetStreamPlayOptions.streamName
RESUME Requests data from the new connection starting from the point at which the previous connection ended.resumeString Requests data from the new connection starting from the point at which the previous connection ended. The RESUME mode aligns the stream across the two connections so no artifacts or jumps are observed in the video playback. Use this mode when you reconnect a stream that was dropped due to server issues or other connection problems. APPEND_AND_WAITNetStream.play2()STOP Stops playing the streams in a playlist.stopString Stops playing the streams in a playlist. This mode does the same thing as calling NetStream.play(false). It stops and resets the playlist. NetStream.play()NetStream.play2()SWAP Replaces a content stream with a different content stream and maintains the rest of the playlist.swapString Replaces a content stream with a different content stream and maintains the rest of the playlist.

This mode replaces the stream specified in NetStreamPlayOptions.oldStreamName with the stream specified in NetStreamPlayOptions.streamName. The rest of the playlist is maintained. In this mode, Flash Media Server does not make assumptions about the content of the streams and treats them like different content.

If oldStreamName has not yet been sent, the server performs the switch at the stream boundary and sends the bits for streamName from the beginning. If the server has already started sending the bits for oldStreamName, it doesn't switch to streamName, and a NetStream.Play.Failed event is sent.

Use this mode if the streams you want to switch are not related to each other and have different content or lengths. For example, use this mode when you want to swap one commercial for another based on user tracking and past commercial-viewing statistics.

To switch from one stream to another with the same content, use the SWITCH mode instead.

SWITCHNetStreamPlayOptions.oldStreamNameNetStreamPlayOptions.streamName
SWITCH Switches from playing one stream to another stream, typically with streams of the same content.switchString Switches from playing one stream to another stream, typically with streams of the same content. Specify the streams to switch in NetStreamPlayOptions.oldStreamName and NetStreamPlayOptions.streamName.

Use this mode when you want to switch to a stream that has the same content but is encoded at a different bit rate or resolution. For example, use this mode when the application queues up streams in a playlist or is playing a single stream at a particular bit rate, then calculates that the bandwidth availability or the CPU capability is either lower or higher than the stream requirements. The application can then update the streams with their higher or lower bit rate versions.

In this mode, Flash Media Server makes certain assumptions about the relationship between the oldStreamName and streamName streams. The server assumes that the streams contain the same content and have the same keyframe interval but have different resolutions or bit rates.

When a playlist has been queued up and oldStreamName is one of the streams in the playlist or is currently playing, oldStreamName is replaced by streamName.

If oldStreamName is null or undefined, or if it is not found in the playlist, the server switches to streamName at the next logical point, to ensure a smooth switch.

To switch from one stream to another with different content, use the SWAP mode instead.

SWAPNetStreamPlayOptions.oldStreamNameNetStreamPlayOptions.streamName
NetConnection The NetConnection class creates a two-way connection between a client and a server.flash.events:EventDispatcher The NetConnection class creates a two-way connection between a client and a server. The client can be a Flash Player or AIR application. The server can be a web server, Flash Media Server, an application server running Flash Remoting, or the Adobe Stratus service. Call NetConnection.connect() to establish the connection. Use the NetStream class to send streams of media and data over the connection.

For security information about loading content and data into Flash Player and AIR, see the following:

  • To load content and data into Flash Player from a web server or from a local location, see Flash Player Developer Center: Security.
  • To load content and data into Flash Player and AIR from Flash Media Server, see the Flash Media Server documentation.
  • To load content and data into AIR, see the Adobe AIR Developer Center.

To write callback methods for this class, extend the class and define the callback methods in the subclass, or assign the client property to an object and define the callback methods on that object.

The following example uses a Video object with the NetConnection and NetStream classes to load and play an FLV 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 = "http://www.helpexamples.com/flash/video/cuepoints.flv"; private var connection:NetConnection; private var stream:NetStream; private var video:Video = new Video(); 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(); 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); } }
clientNetStreamconnect()flash.net.RespondernetStatus Dispatched when a NetConnection object is reporting its status or error condition.flash.events.NetStatusEvent.NET_STATUSflash.events.NetStatusEvent 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. flash.events.NetStatusEvent.infosecurityError Dispatched if a call to NetConnection.call() attempts to connect to a server outside the caller's security sandbox.flash.events.SecurityErrorEvent.SECURITY_ERRORflash.events.SecurityErrorEvent Dispatched if a call to NetConnection.call() attempts to connect to a server outside the caller's security sandbox. NetConnection.call()ioError Dispatched when an input or output error occurs that causes a network operation to fail.flash.events.IOErrorEvent.IO_ERRORflash.events.IOErrorEvent Dispatched when an input or output error occurs that causes a network operation to fail. asyncError Dispatched when an exception is thrown asynchronously &#x2014; that is, from native asynchronous code.flash.events.AsyncErrorEvent.ASYNC_ERRORflash.events.AsyncErrorEvent Dispatched when an exception is thrown asynchronously — that is, from native asynchronous code. NetConnection Creates a NetConnection object. Creates a NetConnection object. Call the connect() method to make a connection.

If an application needs to communicate with servers released prior to Flash Player 9, set the NetConnection object's objectEncoding property.

The following code creates a NetConnection object:

     var nc:NetConnection = new NetConnection();
     
flash.net.NetConnection.connect()objectEncoding
addHeader Adds a context header to the Action Message Format (AMF) packet structure.operationStringIdentifies the header and the ActionScript object data associated with it. mustUnderstandBooleanfalseA value of true indicates that the server must understand and process this header before it handles any of the following headers or messages. paramObjectnullAny ActionScript object. Adds a context header to the Action Message Format (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. call Calls a command or method on Flash Media Server or on an application server running Flash Remoting.commandStringA method specified in the form [objectPath/]method. For example, the someObject/doSomething command tells the remote server to call 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.

With Flash Media Server, command is the name of a function defined in an application's server-side script. You do not need to use an object path before command if the server-side script is placed at the root level of the application directory.

responderflash.net:ResponderAn 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. argumentsOptional 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.
Calls a command or method on Flash Media Server or on an application server running Flash Remoting. Before calling NetConnection.call() you must call NetConnection.connect() to connect to the server. You must create a server-side function to pass to this method.

You cannot connect to commonly reserved ports. For a complete list of blocked ports, see "Restricting Networking APIs" in the ActionScript 3.0 Developer's Guide.

flash.net.RespondersecurityErrorflash.events:SecurityErrorEventA 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. A call attempted to communicate with a server outside the caller's security sandbox.
close Closes the connection that was opened locally or to the server and dispatches a netStatus event with a code property of NetConnection.Connect.Closed. Closes the connection that was opened locally or to the server and dispatches a netStatus event with a code property of NetConnection.Connect.Closed.

This method disconnects all NetStream objects running over the connection. Any queued data that has not been sent is discarded. (To terminate local or server streams without closing the connection, use NetStream.close().) If you close the connection and then want to create a new one, you must create a new NetConnection object and call the connect() method again.

The close() method also disconnects all remote shared objects running over this connection. However, you don't need to recreate the shared object to reconnect. Instead, you can just call SharedObject.connect() to reestablish the connection to the shared object. Also, any data in the shared object that was queued when you issued NetConnection.close() is sent after you reestablish a connection to the shared object.

With Flash Media Server, the best development practice is to call close() when the client no longer needs the connection to the server. Calling close() is the fastest way to clean up unused connections. You can configure the server to close idle connections automatically as a back-up measure. For more information, see the Flash Media Server Configuration and Administration Guide.

NetStreamflash.events.NetStatusEvent.info
connect Creates a two-way connection to an application on Flash Media Server or to Flash Remoting, or creates a two-way network endpoint for RTMFP peer-to-peer group communication.The URI passed to the command parameter is improperly formatted. ArgumentErrorArgumentErrorThe connection failed. This can happen if you call connect() from within a netStatus event handler, which is not allowed. IOErrorflash.errors:IOErrorLocal-with-filesystem SWF files cannot communicate with the Internet. You can avoid this problem by reclassifying the SWF file as local-with-networking or trusted. SecurityErrorSecurityErrorYou cannot connect to commonly reserved ports. For a complete list of blocked ports, see "Restricting Networking APIs" in the ActionScript 3.0 Developer's Guide. SecurityErrorSecurityErrorcommandStringUse one of the following values for the command parameter:
  • To play video and mp3 files from a local file system or from a web server, pass null.
  • To connect to an application server running Flash Remoting, pass a URL that uses the http protocol.
  • (Flash Player 10.1 or AIR 2 or later) To create a serverless network endpoint for RTMFP IP multicast communication, pass the string "rtmfp:". Use this connection type to receive an IP multicast stream from a publisher without using a server. You can also use this connection type to use IP multicast to discover peers on the same local area network (LAN).
  • This connection type has the following limitations:

    Only peers on the same LAN can discover each other.

    Using IP multicast, Flash Player can receive streams, it cannot send them.

    Flash Player and AIR can send and receive streams in a peer-to-peer group, but the peers must be discovered on the same LAN using IP multicast.

    This technique cannot be used for one-to-one communication.

  • To connect to Flash Media Server, pass the URI of the application on the server. Use the following syntax (items in brackets are optional):

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

    Use one of the following protocols: rtmp, rtmpe, rtmps, rtmpt, rtmpte, or rtmfp. If the connection is successful, a netStatus event with a code property of NetConnection.Connect.Success is returned. See the NetStatusEvent.info property for a list of all event codes returned in response to calling connect().

    If the 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 or AIR connects to the application's default instance.

    (Flash Player 10.1 or AIR 2 or later)To create peer-to-peer applications, use the rtmfp protocol.

argumentsOptional parameters of any type passed to the application specified in command. With Flash Media Server, the additional arguments are passed to the application.onConnect() event handler in the application's server-side code. You must define and handle the arguments in onConnect().
Creates a two-way connection to an application on Flash Media Server or to Flash Remoting, or creates a two-way network endpoint for RTMFP peer-to-peer group communication. To report its status or an error condition, a call to NetConnection.connect() dispatches a netStatus event.

Call NetConnection.connect() to do the following:

  • Pass "null" to play video and mp3 files from a local file system or from a web server.
  • Pass an "http" URL to connect to an application server running Flash Remoting. Use the NetServices class to call functions on and return results from application servers over a NetConnection object. For more information, see the Flash Remoting documentation.
  • Pass an "rtmp/e/s" URL to connect to a Flash Media Server application.
  • Pass an "rtmfp" URL to create a two-way network endpoint for RTMFP client-server, peer-to-peer, and IP multicast communication.
  • Pass the string "rtmfp:" to create a serverless two-way network endpoint for RTMFP IP multicast communication.

Consider the following security model:

  • By default, Flash Player or AIR denies access between sandboxes. A website can enable access to a resource by using a URL policy file.
  • Your application can deny access to a resource on the server. In a Flash Media Server application, use Server-Side ActionScript code to deny access. See the Flash Media Server documentation.
  • You cannot call NetConnection.connect() if the calling file is in the local-with-file-system sandbox.
  • You cannot connect to commonly reserved ports. For a complete list of blocked ports, see "Restricting Networking APIs" in the ActionScript 3.0 Developer's Guide.
  • To prevent a SWF file from calling this method, set the allowNetworking parameter of the the object and embed tags in the HTML page that contains the SWF content.

However, in Adobe AIR, content in the application security sandbox (content installed with the AIR application) are not restricted by these security limitations.

For more information about security, see the Adobe Flash Player Developer Center: Security.

flash.net.NetStreamflash.events.NetStatusEvent.info
client Indicates the object on which callback methods are invoked.ObjectThe client property must be set to a non-null object. TypeErrorTypeError Indicates the object on which callback methods are invoked. The default is this NetConnection instance. If you set the client property to another object, callback methods will be invoked on that object. connectedProxyType The proxy type used to make a successful connection to Flash Media Server.StringAn attempt was made to access this property when the NetConnection instance was not connected. ArgumentErrorArgumentError The proxy type used to make a successful connection to Flash Media Server. Possible values are: "none", "HTTP", "HTTPS", or "CONNECT".

The value is "none" if the connection is not tunneled or is a native SSL connection.

The value is "HTTP" if the connection is tunneled over HTTP.

The value is "HTTPS" if the connection is tunneled over HTTPS,

The value is "CONNECT" if the connection is tunneled using the CONNECT method through a proxy server.

connected Indicates whether the application is connected to a server through a persistent RTMP connection (true) or not (false).Boolean Indicates whether the application is connected to a server through a persistent RTMP connection (true) or not (false). When connected through HTTP, this property is false, except when connected to Flash Remoting services on an application server, in which case it is true. defaultObjectEncoding The default object encoding for NetConnection objects.uint The default object encoding for NetConnection objects. When an object is written to or read from binary data, the defaultObjectEncoding property indicates which Action Message Format (AMF) version is used to serialize the data: the ActionScript 3.0 format (ObjectEncoding.AMF3) or the ActionScript 1.0 and ActionScript 2.0 format (ObjectEncoding.AMF0).

The default value is ObjectEncoding.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 application), set the objectEncoding property of the NetConnection object instead.

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

NetConnection.objectEncodingflash.net.ObjectEncoding
farID The identifier of the Flash Media Server instance to which this Flash Player or Adobe AIR instance is connected.String The identifier of the Flash Media Server instance to which this Flash Player or Adobe AIR instance is connected. This property is meaningful only for RTMFP connections. The value of this property is available only after an RTMFP connection is established. nearIDfarNonce A value chosen substantially by Flash Media Server, unique to this connection.String A value chosen substantially by Flash Media Server, unique to this connection. This value appears to the server as its client.nearNonce value. This value is defined only for RTMFP, RTMPE, and RTMPTE connections. httpIdleTimeout The time, in milliseconds, to wait for an HTTP response.NumberThe time in milliseconds to wait for an HTTP response. The time, in milliseconds, to wait for an HTTP response. The default value is zero.
  • The httpIdleTimeout value is a Number.
  • When using an HTTP connection, a positive value indicates the number of milliseconds an inactive connection should remain open.
  • A value of zero indicates that the default networking idle timeout value for the platform should be used.
  • A negative value will result in a RangeError.
  • If the httpIdleTimeout value is exceeded, a netStatus event is dispatched.
  • This property will only affect NetConnection objects created with HTTP connections. NetConnection objects created with RTMP, RTMFP, or other HTTP channels remain unaffected by this property.
//Set the timeout to 5 seconds connection = new NetConnection(); connection.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler); connection.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler); connection.httpIdleTimeout = 5000; In Linux-based systems, the NetConnection may take more seconds to timeout than what is specified using the httpIdleTimeout value.
maxPeerConnections The total number of inbound and outbound peer connections that this instance of Flash Player or Adobe AIR allows.uint The total number of inbound and outbound peer connections that this instance of Flash Player or Adobe AIR allows. The default value is 8.

This value does not distinguish between publisher and subscriber connections. If this value is reduced while peer connections are present, the new value affects new incoming connections only. Existing connections are not dropped.

nearID The identifier of this Flash Player or Adobe AIR instance for this NetConnection instance.String The identifier of this Flash Player or Adobe AIR instance for this NetConnection instance. This property is meaningful only for RTMFP connections.

Every NetConnection instance has a unique nearID property. No Flash Player or Adobe AIR instance or NetConnection instance has the same identifier.

Other Flash Player or Adobe AIR instances use this identifier as the peerID for new NetStream connections to this client. Subsequently, this identifier is the farID in any peer NetStream that connects to this instance.

farID
nearNonce A value chosen substantially by this Flash Player or Adobe AIR instance, unique to this connection.String A value chosen substantially by this Flash Player or Adobe AIR instance, unique to this connection. This value appears to the server as its client.farNonce value. This value is defined only for RTMFP, RTMPE, and RTMPTE connections. objectEncoding The object encoding for this NetConnection instance.uintAn attempt was made to set the value of the objectEncoding property while the NetConnection instance was connected. ReferenceErrorReferenceErrorThis property was set to a value other than ObjectEncoding.AMF0 or ObjectEncoding.AMF3. ArgumentErrorArgumentError The object encoding for this NetConnection instance.

When an object is written to or read from binary data, the defaultObjectEncoding property indicates which Action Message Format (AMF) version is used to serialize the data: the ActionScript 3.0 format (ObjectEncoding.AMF3) or the ActionScript 1.0 and ActionScript 2.0 format (ObjectEncoding.AMF0). Set the objectEncoding property to set an AMF version for a NetConnection instance.

It's important to understand this property if your application needs to communicate with servers released prior to Flash Player 9. The following three scenarios are possible:

  • Connecting to a server that supports AMF3 (for example, Flex Data Services 2 or Flash Media Server 3). The default value of defaultObjectEncoding is ObjectEncoding.AMF3. All NetConnection instances created in this file use AMF3 serialization, so you don't need to set the objectEncoding property.
  • Connecting to a server that doesn't support AMF3 (for example, Flash Media Server 2). In this scenario, set the static NetConnection.defaultObjectEncoding property to ObjectEncoding.AMF0. All NetConnection instances created in this SWF file use AMF0 serialization. You don't need to set the objectEncoding property.
  • Connecting to multiple servers that use different encoding versions. Instead of using defaultObjectEncoding, set the object encoding on a per-connection basis using the objectEncoding property for each connection. Set it to ObjectEncoding.AMF0 to connect to servers that use AMF0 encoding, such as Flash Media Server 2, and set it to ObjectEncoding.AMF3 to connect to servers that use AMF3 encoding, such as Flex Data Services 2.

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

If you use the wrong encoding to connect to a server, the NetConnection object 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.

defaultObjectEncodingflash.net.ObjectEncoding
protocol The protocol used to establish the connection.StringAn attempt was made to access this property when the NetConnection instance was not connected. ArgumentErrorArgumentError The protocol used to establish the connection. This property is relevant when using Flash Media Server. Possible values are as follows:
  • "rtmp": Real-Time Messaging Protocol (RTMP)
  • "rtmpe": Encrypted RTMP
  • "rtmpt": HTTP tunneling RTMP
  • "rtmpte": HTTP tunneling encrypted RTMP
  • "rtmps": HTTPS-based RTMP
  • "rtmfp": Real-Time Media Flow Protocol (RTMFP)
proxyType Determines which fallback methods are tried if an initial connection attempt to Flash Media Server fails.String Determines which fallback methods are tried if an initial connection attempt to Flash Media Server fails. Set the proxyType property before calling the NetConnection.connect() method.

Acceptable values are "none", "HTTP", "CONNECT", and "best".The default value is "none".

To use native SSL, set the property to "best". If the player cannot make a direct connection to the server (over the default port of 443 or over another port that you specify) and a proxy server is in place, the player tries to use the CONNECT method. If that attempt fails, the player tunnels over HTTPS.

If the property is set to "HTTP" and a direct connection fails, 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 does not fall back to HTTP tunneling.

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.

unconnectedPeerStreams An object that holds all of the peer subscriber NetStream objects that are not associated with publishing NetStream objects.Array An object that holds all of the peer subscriber NetStream objects that are not associated with publishing NetStream objects. Subscriber NetStream objects that are associated with publishing NetStream objects are in the NetStream.peerStreams array. NetStream.peerStreamsuri The URI passed to the NetConnection.connect() method.String The URI passed to the NetConnection.connect() method. If NetConnection.connect() hasn't been called or if no URI was passed, this property is undefined. usingTLS Indicates whether a secure connection was made using native Transport Layer Security (TLS) rather than HTTPS.BooleanAn attempt was made to access this property when the NetConnection instance was not connected. ArgumentErrorArgumentError 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.