Application class

Every instance of a Adobe Media Server application has an Application object, which is a single instance of the Application class. You don’t need to use a constructor function to create an Application object; it is created automatically when an application is instantiated by the server.

Use the Application object to accept and reject client connection attempts, to register and unregister classes and proxies, and to manage the life cycle of an application. The Application object has callback functions that are invoked when an application starts and stops and when a client connects and disconnects.

Availability

Flash Communication Server 1

Property summary

Property

Description

A boolean value that lets administrators access an application with the Administration API approveDebugSession() method (true) or not (false).

Read-only; an Array object containing a list of all the clients connected to an application.

Provides access to properties of the ApplicationObject element in the Application.xml configuration file.

Read-only; the host name of the server for default virtual hosts; the virtual host name for all other virtual hosts.

Read-only; the name of the application instance.

Read-only; the platform and version of the server.

Method summary

Method

Description

application.acceptConnection()

Accepts a connection call from a client to the server.

application.broadcastMsg()

Broadcasts a message to all clients connected to an application instance.

application.clearSharedObjects()

Deletes persistent shared objects files (FSO files) specified by the soPath parameter and clears all properties from active shared objects (persistent and nonpersistent).

application.clearStreams()

Clears recorded streams files associated with an application instance.

application.denyPeerLookup()

Specifies to the server that a peer lookup request has been denied.

application.disconnect()

Terminates a client connection to the application.

application.gc()

Invokes the garbage collector to reclaim any unused resources for this application instance.

application.getStats()

Returns statistics about an application.

application.redirectConnection()

Rejects a connection and provides a redirect URL.

application.registerClass()

Registers a constructor function that is used when deserializing an object of a certain class type.

application.registerProxy()

Maps a method call to another function.

application.rejectConnection()

Rejects the connection call from a client to the server.

application.sendPeerRedirect()

When a peer issues a lookup for a target peer, this method sends the peer an Array of addresses for the target peer.

application.shutdown()

Unloads the application instance.

Event handler summary

Event handler

Description

application.onAppStart()

Invoked when the server loads an application instance.

application.onAppStop()

Invoked when the server is about to unload an application instance.

application.onConnect()

Invoked when NetConnection.connect() is called from the client.

application.onConnectAccept()

Invoked when a client successfully connects to an application; for use with version 2 components only.

application.onConnectReject()

Invoked when a connection is rejected in an application that contains components.

application.onDisconnect()

Invoked when a client disconnects from an application.

application.onPeerLookup()

Invoked when the server receives a lookup request.

application.onPublish()

Invoked when a client publishes a stream to an application.

application.onStatus()

Invoked when the server encounters an error while processing a message that was targeted at this application instance.

application.onUnpublish()

Invoked when a client stops publishing a stream to an application.

application.acceptConnection()

 application.acceptConnection(clientObj)

Accepts a connection call from a client to the server.

Availability

Flash Communication Server 1

Parameters

clientObj

A Client object; a client to accept.

Details

When NetConnection.connect() is called from the client side, it passes a Client object to application.onConnect() on the server. Call application.acceptConnection() in an application.onConnect() event handler to accept a connection from a client. When this method is called, NetConnection.onStatus() is invoked on the client with the info.code property set to "NetConnection.Connect.Success".

You can use the application.acceptConnection() method outside an application.onConnect() event handler to accept a client connection that had been placed in a pending state (for example, to verify a user name and password).

When you call this method, NetConnection.onStatus() is invoked on the client with the info.code property set to "NetConnection.Connect.Success". For more information, see the NetStatusEvent.info property in the ActionScript 3.0 Language and Components Reference or the NetConnection.onStatus() entry in the Adobe Media Server ActionScript 2.0 Language Reference.

Note:

When you use version 2 components, the last line (in order of execution) of the onConnect() handler should be either application.acceptConnection() or application.rejectConnection() (unless you’re leaving the application in a pending state). Also, any logic that follows acceptConnection() or rejectConnection() must be placed in the application.onConnectAccept() and application.onConnectReject() handlers, or it will be ignored.

Example

The following server-side code accepts a client connection and traces the client ID:

 application.onConnect = function(client){ 
     // Accept the connection. 
         application.acceptConnection(client); 
     trace("connect: " + client.id); 
 };
Note:

This example shows code from an application that does not use components.

application.allowDebug

 application.allowDebug

A boolean value that lets administrators access an application with the Administration API approveDebugSession() method (true) or not (false). A debug connection lets administrators view information about shared objects and streams in the Administration Console.

The default value for this property is false and is set in the Application.xml file:

 <Application> 
     ... 
     <Debug> 
         <AllowDebugDefault>false</AllowDebugDefault> 
     </Debug> 
     ... 
 </Application>

Setting application.allowDebug to true in a server-side script overrides the value in the Application.xml file. To view information in the Administration Console about the shared objects and streams in an application, add the following line to your code:

application.allowDebug = true;

Availability

Flash Media Server 2

application.broadcastMsg()

 application.broadcastMsg(cmd [, p1,..., pN])

Broadcasts a message to all clients connected to an application instance. To handle the message, the client must define a handler on the NetConnection object with the same name as the cmd parameter.

In ActionScript 2.0, define the method on the NetConnection object. In ActionScript 3.0, assign the NetConnection.client property to an object on which callback methods are invoked. Define the method on that object.

Availability

Flash Media Server 2

Parameters

cmd

A string; the name of the a handler on the client-side NetConnection object.

p1,..., pN

A string; messages to broadcast.

Example

The following server-side code sends a message to the client:

 application.broadcastMsg("serverMessage", "Hello Client");

The following client-side ActionScript 2.0 code handles the message and outputs “Hello Client”:

 nc = new NetConnection(); 
 nc.serverMessage = function(msg){ 
     trace(msg);  
 };

The following client-side ActionScript 3.0 code handles the message and outputs “Hello Client”:

var nc:NetConnection = new NetConnection() 
var ncClient = new Object(); 
nc.client = ncClient; 
ncClient.serverMessage = nc_serverMessage; 
function nc_serverMessage(msg:String):void{ 
    trace(msg); 
}

application.clearSharedObjects()

 application.clearSharedObjects(soPath)

Deletes persistent shared objects files (FSO files) specified by the soPath parameter and clears all properties from active shared objects (persistent and nonpersistent). Even if you have deleted all the properties from a persistent shared object, unless you call clearSharedObjects(), the FSO file still exists on the server.

Availability

Flash Communication Server 1

Parameters

soPath

A string indicating the Uniform Resource Identifier (URI) of a shared object.

The soPath parameter specifies the name of a shared object, which can include a slash (/) as a delimiter between directories in the path. The last element in the path can contain wildcard patterns (for example, a question mark [?] and an asterisk [*]) or a shared object name. The application.clearSharedObjects() method traverses the shared object hierarchy along the specified path and clears all the shared objects. Specifying a slash (/) clears all the shared objects that are associated with an application instance.

If soPath matches a shared object that is currently active, all its properties are deleted, and a clear event is sent to all subscribers of the shared object. If it is a persistent shared object, the persistent store is also cleared.

The following values are possible for the soPath parameter:

  • / clears all local and persistent shared objects associated with the instance.

  • /foo/bar clears the shared object /foo/bar; if bar is a directory name, no shared objects are deleted.

  • /foo/bar/* clears all shared objects stored under the instance directory /foo/bar. If no persistent shared objects are in use within this namespace, the bar directory is also deleted.

  • /foo/bar/XX?? clears all shared objects that begin with XX, followed by any two characters. If a directory name matches this specification, all the shared objects within this directory are cleared.

Returns

A boolean value of true if the shared object at the specified path was deleted; otherwise, false. If wildcard characters are used to delete multiple files, the method returns true only if all the shared objects that match the wildcard pattern were successfully deleted; otherwise, it returns false.

Example

The following example clears all the shared objects for an instance:

 function onApplicationStop(){ 
     application.clearSharedObjects("/"); 
 }

application.clearStreams()

 application.clearStreams(streamPath)

Clears recorded streams files associated with an application instance. You can use this method to clear a single stream, all streams associated with the application instance, just those streams in a specific subdirectory of the application instance, or just those streams whose names match a specified wildcard pattern.

If the clearStreams() method is invoked on a stream that is currently recording, the recorded file is set to length 0 (cleared), and the internal cached data is also cleared.

A call to application.clearStreams() invokes the Stream.onStatus() handler and passes it an information object that contains information about the success or failure of the call.

Note:

You can also use the Administration API removeApp() method to delete all the resources for a single application instance.

Availability

Flash Communication Server 1

Parameters

streamPath

A string indicating the Uniform Resource Identifier (URI) of a stream.

The streamPath parameter specifies the location and name of a stream relative to the directory of the application instance. You can include a slash (/) as a delimiter between directories in the path. The last element in the path can contain wildcard patterns (for example, a question mark [?] and an asterisk [*]) or a stream name. The clearStreams() method traverses the stream hierarchy along the specified path and clears all the recorded streams that match the given wildcard pattern. Specifying a slash clears all the streams that are associated with an application instance.

To clear FLV, F4V, or MP3 files, precede the stream path with flv:, mp4:, or mp3:. When you specify flv: or mp3: you don’t have to specify a file extension; .flv and .mp3 are implied. However, when you call application.clearStreams("mp4:foo"), the server deletes any file with the name “foo” in an MPEG-4 container; for example, foo.mp4, foo.mov, and foo.f4v. To delete a specific file, pass the file extension in the call; for example, application.clearStreams("mp4:foo.f4v").

Note: If you don't precede the stream path with a file type, only FLV files are deleted.

The following examples show some possible values for the streamPath parameter:

  • flv:/ clears all FLV streams associated with the application instance.

  • mp3:/ clears all MP3 files associated with the application instance.

  • mp4:/ clears all F4V streams associated with the application instance (for example, foo.mp4, foo.f4v, and so on).

  • mp4:foo.mp4 clears the foo.mp4 file.

  • mp4:foo.mov clears the foo.mov file.

  • mp3:/mozart/requiem clears the MP3 file named requiem.mp3 from the application instance’s /mozart subdirectory.

  • mp3:/mozart/* clears all MP3 files from the application instance’s /mozart subdirectory.

  • /report clears the report.flv stream file from the application instance directory.

  • /presentations/intro clears the recorded intro.flv stream file from the application instance’s /presentations subdirectory; if intro is a directory name, no streams are deleted.

  • /presentations/* clears all FLV files from the application instance’s /presentations subdirectory. The /presentation subdirectory is also deleted if no streams are used in this namespace.

  • /presentations/report?? clears all FLV files that begin with “report,” followed by any two characters. If there are directories within the given directory listing, the directories are cleared of any streams that match report??.

Returns

A boolean value of true if the stream at the specified path was deleted; otherwise, false. If wildcard characters are used to clear multiple stream files, the method returns true only if all the streams that match the wildcard pattern were successfully deleted; otherwise, it returns false.

Example

The following example clears all recorded streams:

 function onApplicationStop(){ 
     application.clearStreams("/"); 
 }

The following example clears all MP3 files from the application instance’s /disco subdirectory:

 function onApplicationStop(){ 
     application.clearStreams("mp3:/disco/*"); 
 }

Removing all HDS segments

To remove all the existing HDS segments when the application unloads, you can use the clearOnAppStop tag as shown below:

<JSEngine> 
            <ApplicationObject> 
                <config> 
                    <clearOnAppStop>true</clearOnAppStop>                </config> 
            </ApplicationObject> 
</JSEngine>

application.clients

 application.clients

Read-only; an Array object containing a list of all the clients connected to an application. Each element in the array is a reference to the Client object; use the application.clients.length property to determine the number of users connected to an application.

Do not use the index value of the clients array to identify users between calls, because the array is compacted when users disconnect and the slots are reused by other Client objects.

Availability

Flash Communication Server 1

Example

The following example uses a for loop to iterate through each element in the application.clients array and calls the serverUpdate() method on each client:

 for (i = 0; i < application.clients.length; i++){ 
     application.clients[i].call("serverUpdate"); 
 }

application.config

 application.config

Provides access to properties of the ApplicationObject element in the Application.xml configuration file. To access properties that you set in the configuration file, use the application.config property. For example, to set the value of the password element, use the code application.config.password.

Availability

Flash Media Server 2

Example

Use this sample section from an Application.xml file for this example:

 <Application> 
     <ScriptEngine> 
             <ApplicationObject> 
                 <config> 
                 <user_name>jdoe</user_name> 
                 <dept_name>engineering</dept_name>  
             </config> 
             </ApplicationObject> 
     </ScriptEngine> 
 </Application>

note: You must use the <ScriptEngine> tag as <JSEngine> tag is deprecated.

The following lines of code access the user_name and dept_name properties:

 trace("I am " + application.config.user_name + " and I work in the " + application.config.dept_name + " department."); 
  
 trace("I am " + application.config["user_name"] + " and I work in the " + application.config["dept_name"] + " department.");

The following code is sent to the application log file and the Administration Console:

 I am jdoe and I work in the engineering department.

application.denyPeerLookup()

 application.denyPeerLookup(tag:ByteArray)

Specifies to the server that a peer lookup request has been denied. A call to denyPeerLookup() increments the rtmfp_lookups_deny statistic in the getServerStats()Administration API. This call also logs a message specifying the lookup parameters.

For more information, see Filter introduction requests in the Adobe Media Server Developer’s Guide.

Availability

Flash Media Server 4.5

Parameters

tag

ByteArray; The event.tag received in the lookup request.

Returns

Nothing.

application.disconnect()

 application.disconnect(clientObj)

Terminates a client connection to the application. When this method is called, NetConnection.onStatus() is invoked on the client with info.code set to "NetConnection.Connect.Closed". The application.onDisconnect() handler is also invoked.

Availability

Flash Communication Server 1

Parameters

clientObj

A Client object indicating the client to disconnect. The object must be a Client object from the application.clients array.

Returns

A boolean value of true if the disconnection was successful; otherwise, false.

Example

The following example calls application.disconnect() to disconnect all users from an application instance:

 function disconnectAll(){ 
     for (i=0; i < application.clients.length; i++){ 
         application.disconnect(application.clients[i]); 
     } 
 }

application.gc()

 application.gc()

Invokes the garbage collector to reclaim any unused resources for this application instance.

Availability

Flash Media Server 2

application.getStats()

 application.getStats()

Returns statistics about an application.

Availability

Flash Communication Server 1

Returns

An Object whose properties contain statistics about the application instance. The following table describes the properties:

Property

Description

bw_in

Total number of kilobytes received.

bw_out

Total number of kilobytes sent.

bytes_in

Total number of bytes sent.

bytes_out

Total number of bytes received.

Note: For billing, use the sc-bytes field in the Access log.

msg_in

Total number of Real-Time Messaging Protocol (RTMP) messages sent.

msg_out

Total number of RTMP messages received.

msg_dropped

Total number of RTMP messages dropped.

server_bytes_in

Total number of bytes received by the server.

server_bytes_out

Total number of bytes sent by the server.

total_connects

Total number of clients connected to an application instance.

total_disconnects

Total number of clients who have disconnected from an application instance.

Example

The following example outputs application statistics to the Live Log panel in the Administration Console:

 function testStats(){ 
     var stats = application.getStats(); 
     for(var prop in stats){ 
          trace("stats." + prop + " = " + stats[prop]); 
     } 
 } 
  
 application.onConnect = function(client){ 
     this.acceptConnection(client);  
     testStats();     
 };

application.hostname

 application.hostname

Read-only; the host name of the server for default virtual hosts; the virtual host name for all other virtual hosts.

If an application is running on the default virtual host, and if a value is set in the ServerDomain element in the Server.xml configuration file, the application.hostname property contains the value set in the ServerDomain element. If a value has not been set in the ServerDomain element, the property is undefined.

If an application is running on any virtual host other than the default, the application.hostname property contains the name of the virtual host.

Availability

Flash Communication Server 1.5

application.name

 application.name

Read-only; the name of the application instance.

Availability

Flash Communication Server 1

Example

The following example checks the name property against a specific string before it executes some code:

 if (application.name == "videomail/work"){ 
     // Insert code here. 
 }

application.onAppStart()

 application.onAppStart = function (){}

Invoked when the server first loads the application instance. Use this handler to initialize an application state. The onAppStart() event is invoked only once during the lifetime of an application instance.

Availability

Flash Communication Server 1

Example

 application.onAppStart = function (){ 
     trace ("*** sample_guestbook application start"); 
  
     // Create a reference to a persistent shared object. 
     application.entries_so = SharedObject.get("entries_so", true); 
      
     // Prevent clients from updating the shared object. 
     application.entries_so.lock(); 
      
     // Get the number of entries saved in the shared object 
     // and save it in application.lastEntry.         
     var maxprop = 0; 
     var soProperties = application.entries_so.getPropertyNames(); 
     trace("soProperties:" + soProperties); 
     if (soProperties == null) { 
         application.lastEntry = 0; 
     } else { 
         for (var prop in soProperties) { 
             maxprop = Math.max (parseInt(prop), maxprop); 
             trace("maxprop " + maxprop); 
         } 
         application.lastEntry = maxprop+1; 
     } 
     // Allow clients to update the shared object. 
     application.entries_so.unlock(); 
     trace("*** onAppStart called."); 
 };

application.onAppStop()

 application.onAppStop = function (info){}

Invoked when the server is about to unload an application instance. You can use onAppStop() to flush the application state or to prevent the application from being unloaded.

Define a function that is executed when the event handler is invoked. If the function returns true, the application is unloaded. If the function returns false, the application is not unloaded. If you don’t define a function for this event handler, or if the return value is not a boolean value, the application is unloaded when the event is invoked.

The Adobe Media Server application passes an information object to the application.onAppStop() event. You can use Server-Side ActionScript to look at this information object to decide what to do in the function you define. You can also use the application.onAppStop() event to notify users before shutdown.

If you use the Administration Console or the Server Administration API to unload a Adobe Media Server application, application.onAppStop() is not invoked. Therefore you cannot use application.onAppStop() to tell users that the application is exiting.

When an application doesn’t have incoming client connections, the server considers the application idle and unloads it. To prevent this, define an Application.onAppStop() handler that returns false.

Availability

Flash Communication Server 1

Parameters

info

An Object, called an information object, with properties that explain why the application is about to stop running. The information object has a code property and a level property.

Code property

Level property

Description

Application.Shutdown

status

The application instance is about to shut down.

Application.GC

status

The application instance is about to be destroyed by the server.

Returns

The value returned by the function you define, if any, or null. To unload the application, return true or any non-false value. To refuse to unload the application, return false.

Example

The following example flushes the entries_so shared object when the application stops:

 application.onAppStop = function (info){ 
     trace("*** onAppStop called."); 
     if (info==”Application.Shutdown”){ 
         application.entries_so.flush(); 
     } 
 }

application.onConnect()

 application.onConnect = function (clientObj [, p1, ..., pN]){}

Invoked when NetConnection.connect() is called from the client. This handler is passed a Client object representing the connecting client. Use the Client object to perform actions on the client in the handler. For example, use this function to accept, reject, or redirect a client connection, perform authentication, define methods on the Client object to be called remotely from NetConnection.call(), and set the Client.readAccess and Client.writeAccess properties to determine client access rights to server-side objects.

When performing authentication, all of the information required for authentication should be sent from the NetConnection.connect() method to the onConnect() handler as parameters (p1..., pN).

If you don’t define an onConnect() handler, connections are accepted by default.

If there are several simultaneous connection requests for an application, the server serializes the requests so that only one application.onConnect() handler is executed at a time. It’s a good idea to write code for the application.onConnect() function that is executed quickly to prevent a long connection time for clients.

Note:

When you are using the version 2 component framework (that is, when you are loading the components.asc file in your server-side script file), you must use the application.onConnectAccept() method to accept client connections.

Availability

Flash Communication Server 1

Parameters

clientObj

A Client object. This object contains information about the client that is connecting to the application.

p1 ..., pN

Optional parameters passed to the application.onConnect() handler from the client-side NetConnection.connect() method when a client connects to the application.

Returns

A boolean value; true causes the server to accept the connection; false causes the server to reject the connection.

When true is returned, NetConnection.onStatus() is invoked on the client with info.code set to "NetConnection.Connect.Success". When false is returned, NetConnection.onStatus() is invoked on the client with info.code set to "NetConnection.Connect.Rejected".

If null or no value is returned, the server puts the client in a pending state and the client can’t receive or send messages. If the client is put in a pending state, you must call application.acceptConnection() or application.rejectConnection() at a later time to accept or reject the connection. For example, you can perform external authentication by making a NetConnection call in your application.onConnect() event handler to an application server and having the reply handler call application.acceptConnection() or application.rejectConnection(), depending on the information received by the reply handler.

You can also call application.acceptConnection() or application.rejectConnection() in the application.onConnect() event handler. If you do, any value returned by the function is ignored.

Note:

Returning 1 or 0 is not the same as returning true or false. The values 1 and 0 are treated the same as any other integers and do not accept or reject a connection.

A. Client-side ActionScript B. Server-Side ActionScript 

Example

The following examples show three ways to accept or reject a connection in the onConnect() handler:

 (Usage 1) 
 application.onConnect = function (clientObj [, p1, ..., pN]){ 
     // Insert code here to call methods that do authentication. 
     // Returning null puts the client in a pending state. 
     return null;  
 }; 
 (Usage 2) 
 application.onConnect = function (clientObj [, p1, ..., pN]){ 
     // Insert code here to call methods that do authentication. 
     // The following code accepts the connection: 
     application.acceptConnection(clientObj); 
 }; 
 (Usage 3) 
 application.onConnect = function (clientObj [, p1, ..., pN]) 
 { 
     // Insert code here to call methods that do authentication. 
     // The following code accepts the connection by returning true: 
     return true; 
 };

The following example verifies that the user has sent the password “XXXX”. If the password is sent, the user’s access rights are modified and the user can complete the connection. In this case, the user can create or write to streams and shared objects in the user’s own directory and can read or view any shared object or stream in this application instance.

 // This code should be placed in the global scope. 
  
 application.onConnect = function (newClient, userName, password){ 
     // Do all the application-specific connect logic. 
     if (password == "XXXX"){ 
         newClient.writeAccess = "/" + userName; 
         this.acceptConnection(newClient); 
     } else { 
         var err = new Object(); 
         err.message = "Invalid password"; 
         this.rejectConnection(newClient, err); 
     } 
 };

If the password is incorrect, the user is rejected and an information object with a message property set to “Invalid password” is returned to the client side. The object is assigned to infoObject.application. To access the message property, use the following code on the client side:

 ClientCom.onStatus = function (info.application.message){ 
     trace(info.application.message); 
     // Prints "Invalid password" 
     // in the Output panel on the client side. 
 };

application.onConnectAccept()

 application.onConnectAccept = function (clientObj [,p1, ..., pN]){}

Invoked when a client successfully connects to an application; for use with version 2 components only. Use onConnectAccept() to handle the result of an accepted connection in an application that contains components.

Note:

This component set is deprecated and not included with Adobe Media Server versions 4.0 and later. The components are available from www.adobe.com/go/ams_tools.

If you don’t use the version 2 components framework (ActionScript 2.0 components), you can execute code in the application.onConnect() handler after accepting or rejecting the connection. When you use the components framework, however, any code that you want to execute after the connection is accepted or rejected must be placed in the application.onConnectAccept() and application.onConnectReject() event handlers. This architecture allows all of the components to decide whether a connection is accepted or rejected.

Availability

Flash Media Server (with version 2 media components only).

Parameters

clientObj

A Client object; the client connecting to the application.

p1, ..., pN

Optional parameters passed to the application.onConnectAccept() method. These parameters are passed from the client-side NetConnection.connect() method when a client connects to the application; they can be any ActionScript data type.

Example

The following example is client-side code:

 nc = new NetConnection(); 
 nc.connect("rtmp:/test","jlopes"); 
  
 nc.onStatus = function(info) { 
     trace(info.code); 
 }; 
  
 nc.doSomething = function(){ 
     trace("doSomething called!"); 
 }

The following example is server-side code:

 // When using components, always load components.asc. 
 load("components.asc"); 
  
 application.onConnect = function(client, username){ 
     trace("onConnect called"); 
         gFrameworkFC.getClientGlobals(client).username = username; 
     if (username == "hacker") { 
         application.rejectConnection(client); 
     }  
     else { 
         application.acceptConnection(client); 
     } 
 } 
  
 // Code is in onConnectAccept and onConnectReject statements 
 // because components are used. 
 application.onConnectAccept = function(client, username){ 
     trace("Connection accepted for "+username); 
     client.call("doSomething",null); 
 } 
  
 application.onConnectReject = function(client, username){ 
     trace("Connection rejected for "+username); 
 }

application.onConnectReject()

 application.onConnectReject = function (clientObj [,p1, ..., pN]){}

Invoked when a connection is rejected in an application that contains components.

Note:

This component set is deprecated and not included with Flash Media Server versions 4.0 and later. The components are available from www.adobe.com/go/ams_tools.

If you don’t use the version 2 components framework, you can execute code in the application.onConnect() handler after accepting or rejecting a connection. When you use the components framework, however, any code that you want to execute after the connection is accepted or rejected must be placed in the application.onConnectAccept() and application.onConnectReject() framework event handlers. This architecture allows all of the components to decide whether a connection is accepted or rejected.

Availability

Flash Media Server (with version 2 components only)

Parameters

clientObj

A Client object; the client connecting to the application.

p1, ..., pN

Optional parameters passed to the application.onConnectReject() handler. These parameters are passed from the client-side NetConnection.connect() method when a client connects to the application.

Example

The following example is client-side code that you can use for an application:

 nc = new NetConnection(); 
 nc.connect("rtmp:/test","jlopes"); 
  
 nc.onStatus = function(info) { 
     trace(info.code); 
 }; 
  
 nc.doSomething = function(){ 
     trace("doSomething called!"); 
 }

The following example is server-side code that you can include in the main.asc file:

 // When using components, always load components.asc. 
 load( "components.asc" ); 
  
 application.onConnect = function(client, username){ 
     trace("onConnect called"); 
         gFrameworkFC.getClientGlobals(client).username = username; 
     if (username == "hacker") { 
         application.rejectConnection(client); 
     }  
     else { 
         application.acceptConnection(client); 
     } 
 } 
  
 application.onConnectAccept = function(client, username){ 
     trace("Connection accepted for "+username); 
     client.call("doSomething",null); 
 } 
  
 application.onConnectReject = function(client, username){ 
     trace("Connection rejected for "+username); 
 }

application.onDisconnect()

 application.onDisconnect = function (clientObj){}

Invoked when a client disconnects from an application. Use this event handler to flush any client state information or to notify other users that a user is leaving the application. This handler is optional.

Note:

After a client has disconnected from an application, you cannot use this method to send data back to that disconnected client.

Availability

Flash Communication Server 1

Parameters

clientObj

A Client object; a client disconnecting from the application.

Returns

Server ignores any return value.

Example

This example notifies all connected clients when a client disconnects from an application. The client-side FLA file contains an input text field called nameText, a dynamic text field called statusText, and a button called connectButton. The user enters their name in the input text field. The client-side code passes the name to the server in the NetConnection.connect() call, as follows:

nc = new NetConnection(); 
nc.userDisconnects = function(name) { 
    statusText.text = name + ": disconnected"; 
} 
nc.onStatus = function(info){ 
    statusText.text = info.code; 
} 
connectButton.onPress = function() { 
    nc.connect("rtmp://localhost/testapp", nameText.text); 
};

The server-side onConnect() handler receives the user name from the client-side code and assigns it to a property of the Client object. The server passes the Client object to the onDisconnect() handler when a client disconnects from the application. The Client.call() method inside the onDisconnect() handler calls the userDisconnects method on the client and passes it the name of the disconnecting client. The client displays the name of the disconnected user.

application.onConnect = function(client, name){ 
    client.name = name; 
    trace(client.name + ": onConnect"); 
    return true; 
} 
application.onDisconnect = function(client){ 
    for (var i = 0; i < application.clients.length; i++){ 
        application.clients[i].call("userDisconnects", null, client.name); 
    } 
    trace(client.name + ": onDisconnect"); 
}
Note:

To pass optional parameters to the Client.call() method, pass null for the second (responseObject) parameter.

application.onPeerLookup()

 application.onPeerLookup = function (event:Object){}

Invoked when Adobe Media Server receives a request from a client to connect to another peer. The initiating peer is the peer that makes the request. The target peer is the peer to which the initiating peer wants to connect. Both the initiating peer and the target peer can be connected directly to the server or remote. To reply to the peer lookup request, call application.sendPeerRedirect().

Availability

Flash Media Server 4.5

Parameters

event

Object; contains information about the intiating peer and the target peer. Pass the event object in calls to application.sendPeerRedirect(). Pass the event.tag object in calls to Client.introducePeer().

The event object contains the following properties:

Property

Data type

Description

targetPeerID

String

The peerID of the target peer. The initiating peer is attempting to look up and connect to the target peer.

initiatorAddress

String

The IP address of the initiating client. Send redirect information to this address.

tag

ByteArray

A value that uniquely identifies this lookup request.

interfaceID

Number

Identifies the RTMFP interface on which the request was received.

Example

For an example of distributing peer lookup requests across multiple servers, see Distribute peer lookup requests across multiple servers.

See also

application.onPublish()

 application.onPublish = function (clientObj, streamObj){}

Invoked when a client publishes a stream to an application. Use this event handler to send traffic to other servers when you’re building a large-scale live broadcasting application; this is called multipoint publishing. For example, you can support subscribers in multiple geographic locations by sending traffic from the origin server (Server A) in one city to two origin servers in two different cities (Server B and Server C). The following is the workflow for such a scenario:

  1. A client publisher connects to Server A and starts publishing.

  2. Server A receives notifications from the event handler application.onPublish() in a server-side script.

  3. Inside the onPublish() handler, create two NetStream objects to Server B and Server C.

  4. Call the NetStream.publish() method to redirect the publishing data from Server A to Server B and Server C.

  5. Subscribers connecting to Server B and Server C get the same live stream.

In this example, the publishing client connects and publishes only to Server A. The rest of the data flow is handled by logic in the server-side script.

Note:

You cannot change Client object properties in this handler.

Availability

Flash Media Server 3

Parameters

clientObj

A Client object; the client publishing the stream to the application.

streamObj

A Stream object; the stream being published to the application.

Returns

Server ignores any return value.

application.onStatus()

 application.onStatus = function (infoObject){}

Invoked when the server encounters an error while processing a message that was targeted at this application instance. The application.onStatus() handler handles any Stream.onStatus() or NetConnection.onStatus() messages that don’t find handlers. Also, there are a few status calls that come only to application.onStatus().

Availability

Flash Communication Server 1

Parameters

infoObject

An Object with code and level properties that contain information about the status of an application. Some information objects also have details and description properties.The following table describes the information object property values:

Code property

Level property

Description

Application.Script.Error

error

The ActionScript engine has encountered a runtime error.

This information object also has the following properties:

  • filename: name of the offending ASC file.

  • lineno: line number where the error occurred.

  • linebuf: source code of the offending line.

Application.Script.Warning

warning

The ActionScript engine has encountered a runtime warning.

This information object also has the following properties:

  • filename: name of the offending ASC file.

  • lineno: line number where the error occurred.

  • linebuf: source code of the offending line.

Application.Resource.LowMemory

warning

The ActionScript engine is low on runtime memory. This provides an opportunity for the application instance to free some resources or to take suitable action.

If the application instance runs out of memory, it is unloaded and all users are disconnected. In this state, the server does not invoke the application.onDisconnect() event handler or the application.onAppStop() event handler.

Returns

Any value that the callback function returns.

Example

 application.onStatus = function(info){ 
     trace("code: " + info.code + " level: " + info.level); 
     trace(info.code + " details: " + info.details); 
 }; 
 // Application.Script.Warning level: warning

application.onUnpublish()

 application.onUnpublish = function (clientObj, streamObj){}

Invoked when a client stops publishing a stream to an application. Use this event handler with application.onPublish()to send traffic to other servers when you’re building a large-scale, live broadcasting application.

Note:

You cannot change Client object properties in this handler.

Availability

Flash Media Server 3

Parameters

clientObj

A Client object; the client publishing the stream to the application.

streamObj

A Stream object; the stream being published to the application.

Returns

Server ignores any return value.

application.redirectConnection()

 application.redirectConnection(clientObj, url[, description[, errorObj]])

Rejects a connection and provides a redirect URL. You must write logic in the NetConnection.onStatus() handler that detects redirection and passes the new connection URL to the NetConnection.connect() method.

When this method is called, NetConnection.onStatus() is invoked on the client and passed an information object with the following values:

Property

Value

info.code

"NetConnection.Connect.Rejected"

info.description

The value passed in the description parameter; if no value is passed in the parameter, the default value is "Connection failed"

info.ex.code

302

info.ex.redirect

The new connection URL

info.level

"Error"

Availability

Flash Media Server 3

Parameters

clientObj

A Client object specifying a client to reject.

url

A string specifying the new connection URL.

Note: If you omit this parameter, rejectConnection() is called instead.

description

A string that lets you provide more information when a connection is redirected.

errorObj

An object of any type that is sent to the client, explaining the reason for rejection. The errorObj object is available in client-side scripts as the application property of the information object that is passed to the NetConnection.onStatus() call when the connection is rejected.

Example

The following example is server-side code:

 application.onConnect = function(clientObj, count){ 
     var err = new Object(); 
     err.message = "This is being rejected"; 
     err.message2 = "This is the second message. with number description"; 
     if (count == 1){ 
         redirectURI = "rtmp://www.example.com/redirected/fromScript"; 
         redirectDescription = "this is being rejected via Server Side Script."; 
     } 
     else if (count == 2){ 
         redirectURI = "rtmp://www.example2.com/redirected/fromScript"; 
         redirectDescription = "this is being rejected via Server Side Script.";     
     } 
     application.redirectConnection(clientObj, redirectURI, redirectDescription, err);     
 }

The following example is client-side ActionScript 3.0 code:

 var theConnection:NetConnection; 
 var theConnection2:NetConnection; 
 var client:Object = new Object(); 
  
 function init():void{ 
     connect_button.label = "Connect"; 
     disconnect_button.label = "Disconnect"; 
      
     connect_button.addEventListener(MouseEvent.CLICK, buttonHandler); 
     disconnect_button.addEventListener(MouseEvent.CLICK, buttonHandler); 
 } 
  
 function buttonHandler(event:MouseEvent){ 
     switch (event.target){ 
         case connect_button : 
             doConnect(); 
             break; 
         case disconnect_button : 
             disConnect(); 
             break; 
     } 
 } 
 function doConnect(){ 
     makeConnection(theURI.text); 
 } 
  
  
 function disConnect(){ 
     theConnection.close(); 
 }to 
  
 function makeConnection(uri:String){ 
     if (theConnection){ 
         theConnection.close(); 
     } 
     theConnection = new NetConnection(); 
     theConnection.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler); 
     theConnection.client = client; 
     theConnection.connect(uri); 
 } 
  
 function makeConnection2(uri:String){ 
     if (theConnection2){ 
         theConnection2.close(); 
     } 
     theConnection2 = new NetConnection(); 
     theConnection2.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler); 
     theConnection2.client = client; 
     theConnection2.connect(uri); 
 } 
  
 function netStatusHandler(event:NetStatusEvent):void{ 
 //Check the Redirect code and make connection to redirect URI if appropriate. 
     try{ 
         if (event.info.ex.code == 302){ 
             var redirectURI:String; 
             redirectURI = event.info.ex.redirect; 
             if (redirectURI.charCodeAt(redirectURI.length-1) == 13){ 
                 redirectURI = redirectURI.slice(0,(redirectURI.length-1)); 
             } 
             makeConnection2(redirectURI); 
         } 
     } 
 } 
  
 init();

application.registerClass()

 application.registerClass(className, constructor)

Registers a constructor function that is used when deserializing an object of a certain class type. If the constructor for a class is not registered, you cannot call the deserialized object’s methods. This method is also used to unregister the constructor for a class. This is an advanced use of the server and is necessary only when sending ActionScript objects between a client and a server.

The client and the server communicate over a network connection. Therefore, if you use typed objects, each side must have the prototype of the same objects they both use. In other words, both the client-side and Server-Side ActionScript must define and declare the types of data they share so that there is a clear, reciprocal relationship between an object, method, or property on the client and the corresponding element on the server. You can call application.registerClass() to register the object’s class type on the server side so that you can use the methods defined in the class.

Constructor functions should be used to initialize properties and methods; they should not be used for executing server code. Constructor functions are called automatically when messages are received from the client and need to be “safe” in case they are executed by a malicious client. You shouldn’t define procedures that could result in negative situations, such as filling up the hard disk or consuming the processor.

The constructor function is called before the object’s properties are set. A class can define an onInitialize() method, which is called after the object has been initialized with all its properties. You can use this method to process data after an object is deserialized.

If you register a class that has its prototype set to another class, you must set the prototype constructor back to the original class after setting the prototype. The second example below illustrates this point.

Note:

Client-side classes must be defined as function function_name(){}, as shown in the following examples. If not defined in the correct way, application.registerClass() does not identify the class when its instance passes from the client to the server, and an error is returned.

Availability

Flash Communication Server 1

Parameters

className

A string indicating the name of an ActionScript class.

constructor

A constructor function used to create an object of a specific class type during object deserialization. The name of the constructor function must be the same as className. During object serialization, the name of the constructor function is serialized as the object’s type. To unregister the class, pass the value null as the constructor parameter. Serialization is the process of turning an object into something that you can send to another computer over the network.

Example

The following example defines a Color constructor function with properties and methods. After the application connects, the registerClass() method is called to register a class for the objects of type Color. When a typed object is sent from the client to the server, this class is called to create the server-side object. After the application stops, the registerClass() method is called again and passes the value null to unregister the class.

 function Color(){ 
     this.red = 255; 
     this.green = 0; 
     this.blue = 0; 
 } 
 Color.prototype.getRed = function(){ 
     return this.red; 
 } 
 Color.prototype.getGreen = function(){ 
     return this.green; 
 } 
 Color.prototype.getBlue = function(){ 
     return this.blue; 
 } 
 Color.prototype.setRed = function(value){ 
     this.red = value; 
 } 
 Color.prototype.setGreen = function(value){ 
     this.green = value; 
 } 
 Color.prototype.setBlue = function(value){ 
     this.blue = value; 
 }             
 application.onAppStart = function(){ 
     application.registerClass("Color", Color); 
 };  
 application.onAppStop = function(){ 
     application.registerClass("Color", null); 
 };

The following example shows how to use the application.registerClass() method with the prototype property:

 function A(){} 
 function B(){} 
  
 B.prototype = new A(); 
 // Set constructor back to that of B. 
 B.prototype.constructor = B; 
 // Insert code here. 
 application.registerClass("B", B);

application.registerProxy()

 application.registerProxy(methodName, proxyConnection [, proxyMethodName])

Maps a method call to another function. You can use this method to communicate between different application instances that can be on the same Adobe Media Server or on different Adobe Media Servers. Clients can execute server-side methods of any application instances to which they are connected. Server-side scripts can use this method to register methods to be proxied to other application instances on the same server or a different server. You can remove or unregister the proxy by calling this method and passing null for the proxyConnection parameter, which results in the same behavior as never registering the method at all.

Availability

Flash Communication Server 1

Parameters

methodName

A string indicating the name of a method. All requests to execute methodName for this application instance are forwarded to the proxyConnection object.

proxyConnection

A Client or NetConnection object. All requests to execute the remote method specified by methodName are sent to the Client or NetConnection object specified in the proxyConnection parameter. Any result returned is sent back to the originator of the call. To unregister or remove the proxy, provide a value of null for this parameter.

proxyMethodName

A string indicating the name of a method for the server to call on the object specified by the proxyConnection parameter if proxyMethodName is different from the method specified by the methodName parameter. This is an optional parameter.

Returns

A value that is sent back to the client that made the call.

Example

In the following example, the application.registerProxy() method is called in a function in the application.onAppStart() event handler and is executed when the application starts. In the function block, a new NetConnection object called myProxy is created and connected. The application.registerProxy() method is then called to assign the method getXyz() to the myProxy object.

 application.onAppStart = function(){ 
     var myProxy = new NetConnection(); 
     myProxy.connect("rtmp://xyz.com/myApp"); 
     application.registerProxy("getXyz", myProxy); 
 };

application.rejectConnection()

 application.rejectConnection(clientObj[, description[, errObj])
Note:

The description parameter is supported in Flash Media Server 3 and later.

Rejects the connection call from a client to the server. The application.onConnect() handler is invoked when the client calls NetConnection.connect(). In the application.onConnect() handler, you can either accept or reject the connection. You can also make a call to an application server to authenticate the client before you accept or reject it.

Note:

When you use version 2 components, the last line (in order of execution) of the onConnect() handler should be either application.acceptConnection() or application.rejectConnection() (unless you’re leaving the application in a pending state). Also, any logic that follows acceptConnection() or rejectConnection() must be placed in application.onConnectAccept() and application.onConnectReject() handlers, or it is ignored. This requirement exists only when you use version 2 components.

Availability

Flash Communication Server 1

Parameters

clientObj

A Client object specifying a client to reject.

description

A string that allows you to provide more information when a connection is redirected.

errObj

An object of any type that is sent to the client, explaining the reason for rejection. The errObj object is available in client-side scripts as the application property of the information object that is passed to the NetConnection.onStatus() call when the connection is rejected.

Example

In the following example, the client is rejected and sent an error message. This is the server-side code:

 application.onConnect = function(client){ 
     // Insert code here. 
     var error = new Object();error.message = "Too many connections"; 
     application.rejectConnection(client, error); 
 };

This is the client-side code:

 clientConn.onStatus = function (info){ 
     if (info.code == "NetConnection.Connect.Rejected"){ 
         trace(info.application.message); 
         // Sends the message  
         // "Too many connections" to the Output panel 
         // on the client side. 
     } 
 };

application.sendPeerRedirect()

 application.sendPeerRedirect(redirectAddress:Array, event:Object)

When a peer requests a lookup for a target peer, call this method to send the peer an Array of addresses for the target peer. Call this method from the application.onPeerLookup() callback function.

See Distribute peer introductions across multiple servers.

Availability

Flash Media Server 4.5

Parameters

redirectAddresses

Array; An array of addresses, as Strings, that may be used to contact the target peer.

event

Object; The event object received in the application.onPeerLookup() callback.

See also

application.server

 application.server

Read-only; the platform and version of the server.

Availability

Flash Communication Server 1

Example

The following example checks the server property against a string before executing the code in the if statement:

 if (application.server == "Adobe Media Server-Windows/1.0"){ 
     // Insert code here. 
 }

application.shutdown()

 application.shutdown()

Unloads the application instance. If the application is running in vhost or application-level scope, only the application instance is unloaded, but the core process remains running. If the application is running in instance scope, the application instance is unloaded and the core process terminates. This process is done asynchronously; the instance is unloaded when the unload sequence begins, not when the shutdown() call returns.

After shutdown() is called, application.onAppStop() is called, connected clients are disconnected, and application.onDisconnect() is called for each client. Calls made after calling shutdown() may not be executed.

Availability

Flash Media Server 2

Returns

A boolean value indicating success (true) or failure (false).

More like this

Get help faster and easier

New user?