|
Flash Media Server Resources |
Application classContents [Hide]Every instance of a Flash 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. Property summary
Method summary
Event handler summary
application.acceptConnection()application.acceptConnection(clientObj) Accepts a connection call from a client to the server. DetailsWhen 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 Flash 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.
ExampleThe 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.allowDebugapplication.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; 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. 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. Parameters
ReturnsA 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. 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.
Parameters
application.clientsapplication.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. application.configapplication.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. ExampleUse this sample section from an Application.xml file for this example: <Application>
<JSEngine>
<ApplicationObject>
<config>
<user_name>jdoe</user_name>
<dept_name>engineering</dept_name>
</config>
</ApplicationObject>
</JSEngine>
</Application>
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.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. application.getStats()application.getStats() Returns statistics about an application. ReturnsAn Object whose properties contain statistics about the application instance. The following table describes the properties:
ExampleThe 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.hostnameapplication.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. 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. Exampleapplication.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 Flash 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 Flash Media Server application, application.onAppStop() is not invoked. Therefore you cannot use application.onAppStop() to tell users that the application is exiting. Parameters
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.
Parameters
ReturnsA 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.
ExampleThe 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. 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. Parameters
ExampleThe 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. 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. Parameters
ExampleThe 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.
ExampleThis 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.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:
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.
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(). Parameters
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.
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:
Parameters
ExampleThe 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.
Parameters
ExampleThe 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 Flash Media Server or on different Flash 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. Parameters
ExampleIn 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 Interactive Server 3 and Flash Media Development
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.
Parameters
ExampleIn 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.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. |