Server-Side ActionScript Language Reference
Trademarks 1 Step RoboPDF, ActiveEdit, ActiveTest, Authorware, Blue Sky Software, Blue Sky, Breeze, Breezo, Captivate, Central, ColdFusion, Contribute, Database Explorer, Director, Dreamweaver, Fireworks, Flash, FlashCast, FlashHelp, Flash Lite, FlashPaper, Flash Video Encoder, Flex, Flex Builder, Fontographer, FreeHand, Generator, HomeSite, JRun, MacRecorder, Macromedia, MXML, RoboEngine, RoboHelp, RoboInfo, RoboPDF, Roundtrip, Roundtrip HTML, Shockwave, SoundEdit, Studio MX, UltraDev, and WebHelp are eith
Contents Chapter 1: Server-Side ActionScript Language Reference . . . . . . 5 Using server-side ActionScript . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 Using naming conventions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7 ActionScript classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8 Global functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Contents
CHAPTER 1 1 Server-Side ActionScript Language Reference Server-side ActionScript is a scripting language on the server that lets you develop efficient and flexible client-server Macromedia Flash Media Server applications. For example, you can use server-side ActionScript to control log-in procedures, control events in connected Macromedia Flash applications, determine what users see in their Flash applications, and communicate with other servers.
Create the server-side ActionScript file and name it main.asc. All ActionScript code that is embedded in the script file and not in a function body executes once when the application is loaded but before the application.onAppStart event handler is called. NO TE You can name your server-side ActionScript file app_name, where app_name is the name of your application’s directory, and save it with a file extension of .asc or .js.
4. Place the main.asc file in the appName directory or in a subdirectory called scripts in the appName directory. 5. Open the Flash application (the SWF file) in a browser or in the stand-alone Flash Player. The SWF file must contain ActionScript code that passes appName to the connect method of the NetConnection class, as shown in the following example: nc = new NetConnection(); nc.connect("rtmp://flashcomsvr.mydomain.
Avoiding reserved commands Flash Media Server has reserved commands that you cannot use in a script. These commands are either methods that belong to the client-side NetConnection class or methods that belong to the server-side Client class. This means that if you have a NetConnection object on the client (player), you cannot make the following call: nc.call("reservedCmd", ...
ActionScript class Description Stream class The Stream class lets you handle each stream in a Flash Media Server application. WebService class The WebServices class lets you create and access a WSDL/ SOAP web service. XML class The XML class lets you load, parse, send, build, and manipulate XML document trees. XMLSocket class The XMLSocket class implements client sockets that let Flash Media Server communicate with a server identified by an IP address or domain name.
ActionScript elements Entries in this document are alphabetical by class name and then by method, property, or event handler name. The following table lists all classes, methods, properties, and event handlers individually in alphabetical order. ActionScript element See entry acceptConnection Application.acceptConnection() addHeader NetConnection.addHeader() addRequestHeader LoadVars.addRequestHeader(), XML.addRequestHeader() agent Client.agent allowDebug Application.allowDebug appendChild XML.
ActionScript element See entry config Application.config connect NetConnection.connect(), XMLSocket.connect() contentType LoadVars.contentType, XML.contentType copyTo File.copyTo() createElement XML.createElement() createTextNode XML.createTextNode() creationTime File.creationTime decode LoadVars.decode() detail SOAPFault.detail disconnect Application.disconnect() docTypeDecl XML.docTypeDecl eof File.eof() exists File.exists faultactor SOAPFault.faultactor faultcode SOAPFault.
ActionScript element See entry hostName Application.hostname ignoreWhite XML.ignoreWhite insertBefore XML.insertBefore() ip Client.ip isConnected NetConnection.isConnected isDirectory File.isDirectory isDirty SharedObject.isDirty isFile File.isFile isOpen File.isOpen lastChild XML.lastChild lastModified File.lastModified length File.length, Stream.length() list File.list() load load(), LoadVars.load(), XML.load() loaded LoadVars.loaded, XML.loaded localName XML.
ActionScript element See entry onConnect Application.onConnect, XMLSocket.onConnect onConnectAccept Application.onConnectAccept onConnectReject Application.onConnectReject onData LoadVars.onData, XML.onData, XMLSocket.onData onDisconnect Application.onDisconnect onFault SOAPCall.onFault, WebService.onFault onHTTPStatus LoadVars.onHTTPStatus, XML.onHTTPStatus onLoad LoadVars.onLoad, WebService.onLoad, XML.onLoad onLog Log.onLog onResult SOAPCall.onResult onStatus Application.
ActionScript element See entry referrer Client.referrer registerClass Application.registerClass() registerProxy Application.registerProxy() rejectConnection Application.rejectConnection() remove File.remove() removeNode XML.removeNode() renameTo File.renameTo() request SOAPCall.request __resolve Client.__resolve response SOAPCall.response resyncDepth SharedObject.resyncDepth secure Client.secure seek getGlobal() send LoadVars.send(), SharedObject.send(), Stream.send(), XML.
ActionScript element See entry type File.type unlock SharedObject.unlock() uri NetConnection.uri, Client.uri version SharedObject.version virtualKey Client.virtualKey write File.write() writeAccess Client.writeAccess writeAll File.writeAll() writeByte File.writeByte() writeln File.writeln() xmlDecl XML.xmlDecl Application class Availability Flash Communication Server 1.
Besides the built-in properties of the Application class, you can create other properties of any legal ActionScript type, including references to other ActionScript objects. For example, the following code creates a new property of type Array and a new property of type Number: application.myarray = new Array(); application.num_requests = 1; Method summary for the Application class Method Description Application.acceptConnection() Accepts a connection to an application from a client. Application.
Property Description Application.config Lets you access properties of the ApplicationObject tag in the Application.xml configuration file. Application.hostname Read-only; the host name of the server for default virtual hosts, and virtual host name for non-default virtual hosts. Application.name Read-only; the name of an application instance. Application.server Read-only; the platform and version of the server. Event handler summary for the Application class Event handler Description Application.
Description Method; accepts the connection call from a client to the server. The application.onConnect event handler is invoked on the server side to notify a script when NetConnection.connect() is called from the client side. You can use the application.acceptConnection() method in an application.onConnect event handler to accept a connection from a client. You can use the application.acceptConnection() method outside an application.
Description Property; a Boolean value that allows Administrators to access your application with the approveDebugSession() Server Management API (true) or not (false). A debug connection displays information about shared objects and streams. For information about creating a debug connection, see NetConnection.connect() and approveDebugSession(). Application.broadcastMsg() Availability Flash Media Server 2. Usage application.broadcastMsg(cmd [, p1, p2, ...
See also SharedObject.handlerName Application.clearSharedObjects() Availability Flash Communication Server MX 1.0. Usage application.clearSharedObjects(soPath) Parameters soPath A string that indicates the URI of a shared object. Returns A Boolean value of true if the shared object at the specified path was deleted; otherwise, false.
If you call the clearSharedObjects() method and the specified path 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. Example The following example clears all the shared objects for an instance: function onApplicationStop(){ application.clearSharedObjects("/"); } See also SharedObject.clear() Application.
The streamPath parameter specifies the location and name of a stream, relative to the application’s instance directory. 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 application.clearStreams() method traverses the stream hierarchy along the specified path and clears all the recorded streams that match the given wildcard pattern.
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/*"); } Application.clients Availability Flash Communication Server MX 1.0. Usage application.
Example The following example uses a for loop to iterate through each member of the application.clients array and calls the method serverUpdate on each client: for (i = 0; i < application.clients.length; i++){ application.clients[i].call("serverUpdate"); } Application.config Availability Flash Media Server 2. Usage application.config Description Property; lets you access properties of the ApplicationObject tag in the Application.xml configuration file.
Application.disconnect() Availability Flash Communication Server MX 1.0. Usage application.disconnect(clientObj) Parameters clientObj The client to disconnect. The object must be a Client object from the array. application.clients Returns A Boolean value of true if the disconnect was successful; otherwise, false. Description Method; causes the server to terminate a client connection to the application. When this method is called, NetConnection.
Returns Nothing. Description Method; invokes the garbage collector to reclaim any unused resources for this application instance. Application.getStats() Availability Flash Communication Server MX 1.0. Usage application.getStats() Returns An ActionScript object with various properties for each statistic returned.
Usage application.hostname Description Property (read-only); contains the host name of the server for default virtual hosts and the virtual host name for non-default virtual hosts. Example The following example traces the name of the host running the current application: trace(application.hostname) Application.name Availability Flash Communication Server MX 1.0. Usage application.name Description Property (read-only); contains the name of the Flash Media Server application instance.
Returns Nothing. Description Event handler; invoked when the server first loads the application instance. You use this handler to initialize an application state. You can use application.onAppStart and application.onAppStop to initialize and clean up global variables in an application because each of these events is invoked only once during the lifetime of an application instance. Example The following example defines an anonymous function for the application.
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 could also define the application.onAppStop event to notify users before shutdown. If you use the management console or the Server Management ActionScript API to unload a Flash Media Server application, application.onAppStop is not invoked. Therefore you cannot use the application.
Returns The value you provide. If you return a Boolean value of true, the server accepts the connection; if the value is false, the server rejects the connection. If you return null or no return value, 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.
Accepted client Client-side ActionScript true, acceptConnection acceptConnection NetConnection.connect Server-side ActionScript New Client object (not accepted or rejected yet) Application.onConnect false, rejectConnection none, null Pending client rejectConnection Rejected client How to use application.onConnect to accept, reject, or put a client in a pending state. Description Event handler; invoked on the server side when NetConnection.
If there are several simultaneous connection requests for an application, the server serializes the requests so there is only one application.onConnect handler executing at a time. It is a good idea to write code for the application.onConnect function that executes quickly to prevent a long connection time for clients. N OT E If you are using the Component framework (that is, you are loading the components.asc file in your server-side script file) you must use the Application.
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){ trace(info.application.message); // Prints "Invalid password" // in the Output panel on the client-side. }; See also Application.acceptConnection(), Application.
If you don’t use the Flash Media Server components framework, you can execute code in the application.onConnect handler after accepting or rejecting the connection. When you use the components framework, however, any code you want to execute after the connection is accepted or rejected must be placed in the event handlers application.onConnectAccept and application.onConnectReject. This architecture allows all the components to decide whether a connection is accepted or rejected.
See also Application.acceptConnection(), Application.onConnect, Application.onConnectReject, Application.rejectConnection() Application.onConnectReject Availability Flash Media Server (with communication components only). Usage application.onConnectReject = function (clientObj [,p1, ..., pN]){} Parameters clientObj A Client object; the client connecting to the application. Optional parameters passed to the application.onConnectReject handler.
Example The following example is the client-side code 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 the server-side code you can include in the main.asc file: // When using components, always load components.asc. load( "components.asc" ); application.
Application.onDisconnect Availability Flash Communication Server MX 1.0. Usage application.onDisconnect = function (clientObj){} Parameters clientObj A Client object; a client disconnecting from the application. Returns The server ignores any return value. Description Event handler; invoked when a client disconnects from an application. You can use this event handler to flush any client state information or to notify other users of this event. This event handler is optional.
Returns Any value that the callback function returns. Description Event handler; invoked when the server encounters an error while processing a message that was targeted at this application instance. The application.onStatus event handler is the root for 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. This event handler can be used for debugging messages that generate errors.
Returns Nothing. Description Method; 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.
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.
Application.registerProxy() Availability Flash Communication Server MX 1.0. Usage application.registerProxy(methodName, proxyConnection [, proxyMethodName]) Parameters methodName The name of a method. All requests to execute methodName for this application instance are forwarded to the proxyConnection object. 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.
Example In the following example, the application.registerProxy method is called in a function in the application.onAppStart event handler and executes 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.
When you use components and your code includes an explicit call to application.acceptConnection or application.rejectConnection, the last line (in order of execution) of the onConnect method should be either application.acceptConnection or application.rejectConnection. Also, any logic that follows the explicit acceptConnection or rejectConnection statement must be placed in application.onConnectAccept and application.onConnectReject statements, or it will be ignored.
Application.server Availability Flash Communication Server MX 1.0. Usage application.server Description Property (read-only); contains the platform and the server-version information. Example The following example checks the server property against a string before executing the code in the if statement: if (application.server == "Flash Media Server-Windows/1.0"){ // Insert code here. } Application.shutdown() Availability Flash Media Server 2. Usage application.shutdown() Parameters None.
Description Method; 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.
clearInterval() Availability Flash Communication Server MX 1.0. Usage clearInterval(intervalID) Parameters intervalID A unique ID returned by a previous call to the setInterval() method. Returns Nothing. Description Method (global); cancels a time-out that was set with a call to the setInterval() method. Example The following example creates a function named callback and passes it to the setInterval() method, which is called every 1000 milliseconds and outputs the message “interval called.
Client class Availability Flash Communication Server 1. The Client class lets you handle each user, or client, connection to a Flash Media Server application instance. The server automatically creates a Client object when a user connects to an application; the object is destroyed when the user disconnects from the application. Users have unique Client objects for each application to which they are connected. Thousands of Client objects can be active at the same time.
The previous example works, but must be executed every time a client connects. If you want the same methods and properties to be available to all clients in the application.clients array without defining them every time, you must assign them to the prototype property of the Client class. There are two steps to extending a built-in class using the prototype method. You can write the steps in any order in your script.
Method summary for the Client class Method Description Client.call() Executes a method on the Flash client asynchronously and returns the value from the Flash client to the server. Client.getBandwidthLimit() Returns the maximum bandwidth the client or the server can attempt to use for this connection. Client.getStats() Returns statistics for the client. Client.readAccess Sends a "ping" message to the client. If the client responds, the method returns true; otherwise it returns false. Client.
Event handler summary for the Client class Event handler Description Client."commandName" Invoked when NetConnection.call(commandName) is called in a client-side script. Client.agent Availability Flash Communication Server MX 1.0. Usage clientObject.agent Description Property (read-only); contains the version and platform information of the Flash client. Example The following example checks the agent property against the string "WIN" and executes different code depending on whether they match.
Usage clientObject.call(methodName, [resultObj, [p1, ..., pN]]) Parameters methodName A method specified in the form [objectPath/]method. For example, the command someObj/doSomething tells the client to invoke the NetConnection.someObj.doSomething method on the client. resultObj An optional parameter that is required when the sender expects a return value from the client. If parameters are passed but no return value is desired, pass the value null.
The following server-side script uses the Client.call() method in the application.onConnect handler to call the random() method that was defined on the client side. The server-side script also defines a function called randHander(), which is used in the Client.call() method as the resultObj parameter. application.onConnect = function(clientObj){ trace("we are connected"); application.acceptConnection(clientObj); clientObj.call("random", new randHandler()); }; randHandler = function(){ this.
Example The following example creates a method called sum as a property of the Client object newClient on the server side: newClient.sum = function sum(op1, op2){ return op1 + op2; }; The sum() method can then be called from NetConnection.call() on the Flash client side, as shown in the following example: nc = new NetConnection(); nc.connect("rtmp://myServer/myApp"); nc.call("sum", new result(), 20, 50); function result(){ this.onResult = function (retVal){ output += "sum is " + retVal; }; this.
You can call either of the two functions that were defined in the previous examples (foo and bar) by using the following code in a server-side script: c = new NetConnection(); c.onStatus = function(info) { if(info.code == "NetConnection.Connect.Success") { c.call("foo"); c.call("bar", null, 2, 2); } }; Client.getBandwidthLimit() Availability Flash Communication Server MX 1.0. Usage clientObject.
Client.getStats() Availability Flash Communication Server MX 1.0. Usage clientObject.getStats() Returns An object with various properties for each statistic returned. Description Method; returns statistics for the client including the total number of bytes sent and received, the number of RTMP messages sent and received, the number of dropped RTMP messages, and how long it takes the client takes to respond to a ping message. Example The following example uses Client.
Example The following example uses the Client.ip property to verify whether a new client has a specific IP address. The result determines which block of code runs. application.onConnect = function(newClient, name){ if (newClient.ip == "127.0.0.1"){ // Insert code here. } else { // Insert code here. } }; Client.ping() Availability Flash Communication Server MX 1.0. Usage clientObject.ping() Description Method; sends a “ping” message to the client and waits for a response.
Client.protocol Availability Flash Communication Server MX 1.0 Usage clientObject.protocol Description Property (read-only); a string indicating the protocol used by the client to connect to the server. This string can have one of the following values: (RTMP over a persistent socket connection) ■ rtmp ■ rtmpt (RTMP tunneled using the HTTP protocol) ■ rtmps (RTMP over an SSL connection) For more information about the HTTP tunneling feature in Flash Communication Server MX 1.
Client.readAccess Availability Flash Communication Server MX 1.0. Usage clientObject.readAccess Description Property; a string that provides read-access rights to directories that contain application resources (shared objects and streams) for this client. To give a client read access to directories containing application resources, list directories in a string delimited by semicolons. By default, all clients have full read access, and the readAccess property is set to slash (/).
Client.referrer Availability Flash Communication Server MX 1.0. Usage clientObject.referrer Description Property (read-only); a string whose value is set to the URL of the SWF file or the server in which this connection originated. Example The following example defines an onConnect callback function that sends a trace that indicates the origin of the new client when that client connects to the application: application.
Example The following example defines a function that is called whenever an undefined property is referenced: Client.prototype.__resolve = function (name) { return "Hello, world!"; }; function onConnect(newClient){ // Prints "Hello World". trace (newClient.property1); } Client.secure Availability Flash Media Server 2. Usage clientObject.secure Description Property (read-only); a Boolean value that indicates whether an Internet connection is secure (true) or not (false). See also NetConnection.
Returns Nothing. Description Method; sets the maximum bandwidth for this client from client to server, server to client, or both. The default value for a connection is set for each application in the Application.xml file. The value specified cannot exceed the bandwidth cap value specified in the Application.xml file. Example The following example sets the bandwidth limits for each direction, based on values passed to the onConnect function: application.
Client.virtualKey Availability Flash Media Server 2. Usage clientObject.virtualKey Description Property; the user agent type of the client, which is typically the Flash Player version, but can be set to any legal key value. A legal key can contain be any string that does not contain the characters “*” or “:”. For more information, see Stream.setVirtualPath() on page 158. Client.writeAccess Availability Flash Communication Server MX 1.0. Usage clientObject.
Example The following example provides write access to the /myMedia/myStreams and myData/notes directories. application.onConnect = function(newClient, name){ newClient.writeAccess = "/myMedia/myStreams;myData/notes"; application.acceptConnection(); }; See also Client.readAccess File class Availability Flash Media Server 2. The File class lets applications write to the server’s file system.
■ Root objects cannot be renamed or deleted. For example, if a path using the slash (/) is used to create a File object, the application folder is mapped. ■ Applications can be granted access to additional directories by specifying virtual directory mappings for File object paths. This is done by specifying a FileObject tag within the JSEngine section in the Application.
Method summary for the File class Method Description File.close() Closes the file. File.copyTo() Copies a file to a different location or to the same location with a different filename. File.eof() Returns a Boolean value indicating whether the file pointer is at the end of file (true) or not (false). File.flush() Flushes the output buffers of a file. File.list() If the file is a directory, returns an array with an element for each file in the directory. File.
Property summary for the File class Property Description File.canAppend Read-only; a Boolean value indicating whether a file was open for appending (true) or not (false). File.canRead Read-only; a Boolean value indicating whether a file can be read (true) or not (false). File.canReplace Read-only; a Boolean value indicating whether a file was opened with the replace flag enabled (true) or not (false). File.
Constructor for the File class Availability Flash Media Server 2. Usage fileObject = new File(name) Parameters Specifies the name of the file or directory. The name can contain only UTF-8 encoded characters; high byte values can be encoded using the URI character- encoding scheme. The specified name is mapped to a system path using the mappings specified in the Application.xml file. If the path is invalid, the name property of the object is set to an empty string, and no file operation can be performed.
File.canRead Availability Flash Media Server 2. Usage fileObject.canRead Description Property (read-only); a Boolean value indicating whether a file can be read (true) or not (false). File.canReplace Availability Flash Media Server 2. Usage fileObject.canReplace Description Property (read-only); a Boolean value indicating whether a file was opened in create mode (true) or not (false). This property is undefined for closed files. See also File.open() File.canWrite Availability Flash Media Server 2.
Description Property (read-only); a Boolean value indicating whether you can write to a file (true) or not (false). N OT E If File.open() was called to open the file, the mode in which the file was opened is respected. For example, if the file was opened in read mode, you can read from the file, but you cannot write to the file. File.close() Availability Flash Media Server 2. Usage fileObject.close() Parameters None.
File.copyTo() Availability Flash Media Server 2. Usage fileObject.copyTo(name) Parameters Specifies the name of the destination file. The name can contain only UTF-8 characters; high byte values can be encoded using the URI character-encoding scheme. The name specified is mapped to a system path using the mappings specified in the Application.xml file. If the path is invalid or the destination file doesn’t exist, the operation fails, and the method returns false.
File.eof() Availability Flash Media Server 2. Usage fileObject.eof() Parameters None. Returns A Boolean value. Description Method; returns a Boolean value indicating whether the file pointer is pointing to the end of file (true) or not (false). If the file is closed, the method returns true. Example The following while statement lets you insert code that executes until the file pointer is at the end of a file: while (!myFileObj.eof()){ // Do something here. } File.
File.flush() Availability Flash Media Server 2. Usage fileObject.flush() Parameters Returns A Boolean value; returns a Boolean value indicating whether the flush operation was successful (true) or not (false). Description Method; flushes the output buffers of a file. The operation fails if the file is closed. Example The following if statement lets you insert code that executes if myFileObj flushes successfully: if (myFileObj.flush()){ // Do something here. } File.
The following example uses named property lookup to refer to files that do not have valid property names: mySameFileInDir = myDir["foo"]; myOtherFile = myDir["some long filename with spaces and such"]; File.isFile Availability Flash Media Server 2. Usage fileObject.isFile Description Property (read-only); a Boolean value indicating whether a file is a data file (true) or not (false). File.isOpen Availability Flash Media Server 2. Usage fileObject.
Description Property (read-only); a Date object containing the time the file was last modified. File.length Availability Flash Media Server 2. Usage fileObject.length Description Property (read-only). For a directory, the number of files in the directory, not counting the current directory and parent directory entries; for a file, the number of bytes in the file. File.list() Availability Flash Media Server 2. Usage fileObject.
File.mkdir() Availability Flash Media Server 2. Usage fileObject.mkdir(newDir) Parameters A string indicating the name of the new directory. This name is relative to the current File object instance. newDir Returns A Boolean value indicating success (true) or failure (false). Description Method; creates a directory in the file directory. Example The following example creates a logs directory in the myFileObject instance: if (myFileObject.
File.name Availability Flash Media Server 2. Usage fileObject.name Description Property (read-only); a string indicating the name of the file. The value is an empty string if the File object was created with a invalid path. File.open() Availability Flash Media Server 2. Usage fileObject.open("type","mode") Parameters A string indicating the encoding type for the file.
Returns A Boolean value indicating whether the file opened successfully (true) or not (false). Description Method; opens a file so that you can read from it or write to it. First, you must create a file object and then call the open() method on that object. There are no default values for the type and mode parameters—values must be specified. Example The following if statement lets you insert code that executes when a text file is opened in read mode: if (myFileObject.
Returns A string. Description Method; reads the specified number of characters from a file and returns a string. The operation will fail if the file is opened in binary mode. Example The following code opens a text file in read mode and sets variables for the first 100 characters, a line, and a byte: if (myFileObject.open( "text", "read") ){ strVal = myFileObject.read(100); strLine = myFileObject.readln(); strChar = myFileObject.readByte(); } See also File.readAll(), File.readByte(), File.
File.readByte() Availability Flash Media Server 2. Usage fileObject.readByte() Parameters Returns A number; either a positive integer or -1. Description Method; reads the next byte from the file and returns the numeric value of the next byte or -1 if the operation fails. The operation fails if file is not opened in binary mode. See also File.read(), File.readAll(), File.readln() File.readln() Availability Flash Media Server 2. Usage fileObject.readln() Parameters None. Returns A string.
See also File.read(), File.readAll(), File.readByte() File.remove() Availability Flash Media Server 2. Usage fileObject.remove() Parameters None. Returns A Boolean value indicating whether the file or directory was removed successfully (true) or not (false). Description Method; removes the file or directory specified to by the File object. The method returns false if the file is open, the path points to a root folder, or the directory is not empty.
Parameters The new name for the file or directory. The name can contain only UTF-8 encoded characters; high byte values can be encoded using the URI character-encoding scheme. The specified name is mapped to a system path using the mappings specified in the Application.xml file. If the path is invalid or the destination file doesn’t exist, the operation will fail. name Returns A Boolean value indicating whether the file was renamed or moved successfully (true) or not (false).
Description Method; skips a specified number of bytes and returns the new file position. This method can accept both positive and negative parameters. Example In the following example, if the seek call is successful, the code in the if statement runs: if (fileObj.seek(10) != -1){ // Do something here. } File.toString() Availability Flash Media Server 2. Usage fileObject.toString() Parameters None. Returns A string. Description Method; returns the path to the File object.
Description Property (read-only); a string specifying the type of data or encoding used when a file is opened. The following strings are supported: "text", "utf8", and "binary". The property is undefined for directories and closed files. If the file is opened in “text” mode and UTF-8 BOM (Byte Order Mark) is detected, the type property is set to "utf8". File.write() Availability Flash Media Server 2. Usage fileObject.write(param0, param1,...paramN) Parameters param0, param1,...
File.writeAll() Availability Flash Media Server 2. Usage fileObject.writeAll(array) Parameters An Array object containing all the elements to write to the file. array Returns A Boolean value indicating whether the write was successful (true) or not (false). Description Method; takes an array as a parameter and calls the File.writeln() method on each element in the array. The file contents are buffered internally. The File.flush() method writes the buffer to the file on disk. See also File.
The file contents are buffered internally. The File.flush() method writes the buffer to the file on disk. Example The following example writes byte 65 to the end of the myFileObject file: if (myFileObject.open("text","append")) { myFileObject.writeByte(65); } See also File.write(), File.writeAll(), File.writeln() File.writeln() Availability Flash Media Server 2. Usage fileObject.writeln(param0, param1,...paramN) Parameters param0, param1,...paramN Strings to write to the file.
getGlobal() Availability Flash Media Server 2. Usage getGlobal() Parameters None. Returns Nothing. Description Method (global); provides access to the global object while the secure.asc file is loading. Use the global object to manipulate built-in global functions. To prevent inadvertent access to the global object, always hold its reference in a temporary variable (declared by var); do not hold its reference in a member variable or global variable. This function can only be used in the secure.
load() Availability Flash Communication Server MX 1.0. Usage load(filename) Parameters filename The relative path to an ActionScript file from the main.asc file. Returns Nothing. Description Method (global); loads an ActionScript file in the main.asc file. This method executes only when the ActionScript file is loaded first. The loaded file is compiled and executed after the main.asc file is successfully loaded, compiled, and executed, but before application.onAppStart() is executed.
The LoadVars class works much like the XML class; it uses the load(), send(), and sendAndLoad() methods to communicate with a server. The main difference between the LoadVars class and the XML class is that LoadVars transfers ActionScript name and value pairs, rather than an XML Document Object Model (DOM) tree stored in the XML object. The LoadVars class follows the same security restrictions as the XML class. Method summary for the LoadVars class Method Description LoadVars.
Property summary for the LoadVars class Property Description LoadVars.contentType The MIME type sent to the server when you call the LoadVars.send() or LoadVars.sendAndLoad() method. LoadVars.loaded A Boolean value that indicates whether a LoadVars.load() or LoadVars.sendAndLoad() operation has completed (true) or not (false). Event summary for the LoadVars class Event handler Description LoadVars.
LoadVars.addRequestHeader() Availability Flash Media Server 2. Usage myLoadVars.addRequestHeader(header, headerValue) Parameters header A string or array of strings that represents an HTTP request header name. headerValue A string that represents the value associated with header. Returns Nothing. Description Method; adds or changes HTTP request headers (such as Content-Type or SOAPAction) sent with POST actions.
The following example creates a new LoadVars object that adds a request header called FLASH-UUID. The header contains a variable that the server can check. var my_lv = new LoadVars(); my_lv.addRequestHeader("FLASH-UUID", "41472"); my_lv.name = "Mort"; my_lv.age = 26; my_lv.send("http://flash-mx.com/mm/cgivars.cfm", "_blank", "POST"); LoadVars.contentType Availability Flash Media Server 2. Usage myLoadVars.
Description Method; converts the query string to properties of the specified LoadVars object. This method is used internally by the LoadVars.onData event handler. Most users do not need to call this method directly. If you override the LoadVars.onData event handler, you can explicitly call LoadVars.decode() to parse a string of variables. Example The following example traces the three variables: // Create a new LoadVars object var my_lv = new LoadVars(); //Convert the variable string to properties my_lv.
LoadVars.getBytesTotal() Availability Flash Media Server 2. Usage myLoadVars.getBytesTotal() Parameters None. Returns A Number object. The getBytesTotal() method returns undefined if no load operation is in progress or if a load operation has not been initiated. The getBytesTotal() method also returns undefined if the number of total bytes can’t be determined—for example, if the download was initiated but the server did not transmit an HTTP content-length.
Returns A Boolean value indicating success (true) or failure (false). Description Method; downloads variables from the specified URL, parses the variable data, and places the resulting variables into a LoadVars object (myLoadVars). You can load variables from a remote URL or from a URL in the local file system; the same encoding standards apply to both. Any properties in the myLoadVars object that have the same names as downloaded variables are overwritten.
Example The following example loads a text file and writes information to the log file when the operation completes: var my_lv = new LoadVars(); my_lv.onLoad = function(success) { trace("LoadVars loaded successfully: "+this.loaded); }; my_lv.load("http://www.helpexamples.com/flash/params.txt"); See also LoadVars.onLoad LoadVars.onData Availability Flash Media Server 2. Usage myLoadVars.onData(src){} Parameters src A string or undefined; the raw (unparsed) data from a LoadVars.load() or method call.
Example The following example loads a text file and displays content in a TextArea instance called content_ta when the operation completes. If an error occurs, then information displays in the Output panel. If an error occurs, then information writes to the log file. var my_lv = new LoadVars(); my_lv.onData = function(src) { if (src == undefined) { trace("Error loading content."); return; } content_ta.text = src; }; my_lv.load("content.txt", my_lv, "GET"); LoadVars.
Example The following example shows how to use onHTTPStatus to help with debugging. The example collects HTTP status codes and assigns their value and type to an instance of the LoadVars object. (Notice that this example creates the instance members this.httpStatus and this.httpStatusType at runtime.) The onData handler uses these instance members to trace information about the HTTP response that can be useful in debugging. var myLoadVars = new LoadVars(); myLoadVars.
LoadVars.onLoad Availability Flash Media Server 2. Usage myLoadVars.onLoad(success){} Parameters A Boolean value indicating whether the LoadVars.load() operation ended in success (true) or failure (false). success Description Event handler; invoked when a LoadVars.load() or LoadVars.sendAndLoad() operation has completed. If the variables load successfully, the success parameter is true.
Parameters url A string; the URL to which to upload variables. target A File object. If you use this optional parameter, any returned data is output to the specified File object. If this parameter is omitted, the response is discarded. A string indicating the GET or POST method of the HTTP protocol. The default value is POST. This parameter is optional. method Returns A Boolean value indicating success (true) or failure (false).
Description Method; posts the variables in the myLoadVars object to the specified URL. The server response is downloaded, parsed as variable data, and the resulting variables are placed in the target object. Variables are posted in the same way as LoadVars.send(). Variables are downloaded into target in the same way as LoadVars.load(). See also LoadVars.send() LoadVars.toString() Availability Flash Media Server 2. Usage myLoadVars.toString() Parameters None. Returns A string.
Log class Availability Flash Media Server 2. The Log class lets you create a Log object that can be passed as an optional argument to the constructor for the WebService class. For more information, see “Constructor for the WebService class” on page 164. Event handler summary for the Log class Method Description Log.onLog Invoked when a log message is sent to a log. Constructor for the Log class Availability Flash Media Server 2.
Example The following example creates a new instance of the Log class: newLog = new Log(); Log.onLog Availability Flash Media Server 2. Usage myLog.onLog(message){} Parameters message A log message. Returns Nothing. Description Event handler; invoked when a log message is sent to a log. NetConnection class Availability Flash Communication Server MX 1.0.
Method summary for the NetConnection class Method Description NetConnection.addHeader() Adds a context header. NetConnection.call() Invokes a method or operation on a remote server. NetConnection.close() Closes a server connection. NetConnection.connect() Connects to an application server or another Flash Media Server server. Property summary for the NetConnection class Property Description NetConnection.
Description Constructor; creates a new instance of the NetConnection class. Example The following example creates a new instance of the NetConnection class: newNC = new NetConnection(); NetConnection.addHeader() Availability Flash Communication Server MX 1.0. Usage myNetConn.addHeader(name, mustUnderstand, object) Parameters A string; identifies the header and the ActionScript object data associated with it.
NetConnection.call() Availability Flash Communication Server MX 1.0. Usage myNetConnection.call(methodName, [resultObj, p1, ..., pN]) Parameters methodName A method specified in the form [objectPath/]method. For example, the command someObj/doSomething tells the remote server to invoke the clientObj.someObj.doSomething method, with all the p1, ..., pN parameters. If the object path is missing, clientObj.doSomething() is invoked on the remote server.
The following server-side ActionScript code is on server 2. When the client is connecting, this code checks to see whether it has an argument that is equal to svr1. If the client has that argument, the Sum method is defined so that when the method is called from svr1, svr2 can respond with the appropriate method: application.onConnect = function(clientObj){ if(arg1 == "svr1"){ clientObj.
Example The following code closes the NetConnection instance myNetConn: myNetConn.close(); NetConnection.connect() Availability Flash Communication Server MX 1.0. Usage myNetConnection.connect(URI, [p1, ..., pN]) Parameters URI A URI to connect to. Optional parameters that can be of any ActionScript type, including references to other ActionScript objects. These parameters are sent as connection parameters to the application.onConnect event handler for RTMP connections.
It is good practice to write an application.onStatus callback function and check the NetConnection.isConnected property for RTMP connections to see whether a successful connection was made. For Action Message Format connections, check NetConnection.onStatus. About secure connections Flash Media Server accepts only RTMPS connections on designated secure ports. A port is marked as secure by specifying a minus sign (-) in front of the port in the HostPort tag of the Adaptor.
■ If the Application.allowDebug property is true, the connection is approved. To provide total security against debug connections, set application.allowDebug to false in the application.xml file. This setting overrides debug connections that are approved in server-side code. ■ If the connection is approved, Services.onDebugConnect is invoked. If you can use the onConnect handler to reject the connection.
The following example creates a debug connection: nc_admin = new NetConnection(); nc_admin.connect("rtmp://tc.foo.com/myApp/myConn?_fcs_debugreq_=1234"); nc_admin.call("approveDebugSession", null, "myApp/myConn", 1234); NetConnection.isConnected Availability Flash Communication Server MX 1.0. Usage myNetConnection.isConnected Description Property (read-only); a Boolean value that indicates whether a connection has been made. It is set to true if there is a connection to the server.
Returns Nothing. Description Event handler; invoked every time the status of the NetConnection object changes. For example, if the connection with the server is lost in an RTMP connection, the NetConnection.isConnected property is set to false, and NetConnection.onStatus is invoked with a status message of NetConnection.Connect.closed. For AMF connections, NetConnection.onStatus is used only to indicate a failed connection. Use this event handler to check for connectivity.
protectObject() Availability Flash Media Server 2. Usage protectObject(userObj) Parameters userObj An object to wrap in a C wrapper object. Returns An object. Description Method (global); protects user-defined or built-in objects behind a C wrapper object. The methods of any object that has been passed to the protectObject() function become system calls because application code can never access or inspect the methods directly —only through the wrapper. You can only use this function in the secure.
Example After secure.asc is executed, calls to load() are directed through the user-defined system call, as shown in the following example: var sysobj = {}; sysobj._load = load; // Hide the load function load = null; // Make it unavailable unpriviliged code sysobj.load = function(fname){ // User-defined code to validate/modify fname return this._load(fname); } // Grab the global object var global = getGlobal(); // Now protect our sysobj and make it available as // 'system' globally.
Parameters obj An object. A string; the URL to upload variables. The name of the property that exists in the obj parameter. Setting attributes on nonexistent properties has no effect. propName enumerable One of the following values: true, false, or null. Makes a property enumerable if true or nonenumerable if false; a null value leaves this attribute unchanged. Nonenumerable properties are hidden from enumerations (for var i in obj). One of the following values: true, false, or null.
setInterval() Availability Flash Communication Server MX 1.0. Usage setInterval(function, interval[, p1, ..., pN]) setInterval(object, methodName, interval[, p1, ..., pN]) Parameters The name of a defined ActionScript function or a reference to an anonymous function function. object An object derived from the ActionScript Object object. The name of the method to call on object. methodName interval The time (interval) between calls to function, in milliseconds. p1, ...
The following example uses a named function, callback1, to send the message “interval called” to the server log: function callback1(){ trace("interval called"); } setInterval(callback1, 1000); The following example also uses a named function, callback2, to send the message “interval called” to the server log, but it passes the message to the function as a parameter: function callback2(s){ trace(s); } setInterval(callback2, 1000, "interval called"); SharedObject class Availability Flash Communication Serv
■ Sharing 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 real-time data that is visible to all clients connected to the object, such as a list of users connected to a chat room. 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.
When you get a reference to a proxied shared object, any changes made to the object are sent to the instance that owns the object. The success or failure of any changes are sent using the SharedObject.onSync event handler, if it is defined. The SharedObject.lock() and SharedObject.unlock() methods cannot lock or unlock proxied shared objects.
Property summary for the SharedObject class Property Description SharedObject.autoCommit A Boolean value indicating whether the server periodically commits all persistent shared objects to be stored (true) or not (false). SharedObject.isDirty A Boolean value indicating whether the persistent SharedObject has been modified since the last time it was stored (true) or not (false). SharedObject.name The name of a shared object. SharedObject.
This property is true by default. This can be overridden by specifying the initial state using the following configuration key in the Application.xml file, as shown in the following example: false SharedObject.clear() Availability Flash Communication Server MX 1.0. Usage mySO.clear() Parameters None. Returns Returns true if successful; false otherwise.
Parameters None. Returns Nothing. Description Method; detaches a reference from a shared object. A call to the SharedObject.get() method returns a reference to a shared object instance. The reference is valid until the variable that holds the reference is no longer in use and the script is garbage-collected. To destroy a reference immediately, you can call SharedObject.close(). You can use SharedObject.close() when you don’t want to proxy a shared object any longer.
Description Method (static); stores either a specific persistent shared object instance or all persistent shared object instances with an isDirty property whose value is true. Use this method if the SharedObject.autoCommit property is false and you need to manage when a shared object is stored locally. Example The following code commits all dirty shared objects to local storage when the application stops: application.onAppStop = function (info){ // Insert code here. SharedObject.commit(); } SharedObject.
SharedObject.get() Availability Flash Communication Server MX 1.0. Usage SharedObject.get(name, persistence [, netConnection]) Parameters name Name of the shared object instance to return. A Boolean value: true for a persistent shared object; false for a nonpersistent shared object. If no value is specified, the default value is false. persistence A NetConnection object that represents a connection to an application instance.
You can also call SharedObject.get() to get a reference to a shared object that is in a namespace of another application instance. This instance can be on the same server or on a different server and is called a proxied shared object. To get a reference to a shared object from another instance, create a NetConnection object and use the NetConnection.connect() method to connect to the application instance that owns the shared object.
Example The following example creates a shared object named foo in the function onProcessCmd. The function is passed a parameter, cmd, that is assigned to a property in the shared object. function onProcessCmd(cmd){ // Insert code here. var shObj = SharedObject.get("foo", true); propName = cmd.name; shObj.getProperty (propName, cmd.newAddress); } The following example uses a proxied shared object.
Example The following example gets the value of the name property and passes it to the value variable: value = sharedInfo.getProperty(name); See also SharedObject.setProperty() SharedObject.getPropertyNames() Availability Flash Communication Server MX 1.0. Usage mySO.getPropertyNames() Parameters None. Returns An array of strings that contain all the property names of a shared object. Description Method; enumerates all the property names for a given shared object.
SharedObject.handlerName Availability Flash Communication Server MX 1.0. Usage mySO.onBroadcastMsg = function([p1,..., pN]){} Parameters onBroadcastMsg A property name. p1, ..., pN Optional parameters passed to the handler method if the message contains user-defined parameters. These parameters are the user-defined JavaScript objects passed to the SharedObject.send method. Returns Any return value is ignored by the server.
SharedObject.isDirty Availability Flash Media Server 2. Usage mySO.isDirty Description Property (read-only); a Boolean value indicating whether a persistent shared object has been modified since the last time it was stored (true) or not (false). The SharedObject.commit() method stores shared objects with an isDirty property that is true. This property is always false for non-persistent shared objects. Example The following example saves the so shared object if it has been changed: var so = SharedObject.
Description Method; locks the shared object instance. This method gives the server-side script exclusive access to the shared object; when the SharedObject.unlock() method is called, all changes are batched and one update message is sent, through the SharedObject.onSync handler, to all the clients that subscribe to this shared object. If you nest the SharedObject.lock() and SharedObject.
p1, ..., pN Parameters of any ActionScript type, including references to other ActionScript objects. These parameters are passed to the specified handler when it is executed on the Flash client. Returns A Boolean value. Returns true if the message can be dispatched to the client; false otherwise. Description Method; delivers all change events to a subscribing client as a single message.
The following example shows the receiving client-side script: connection = new NetConnection(); connection.connect("rtmp://flashmediaserver/someApp"); var x = SharedObject.get( "foo", connection.uri, true); x.connect(connection); x.onAdrChange = function(str) { // Shared Object has been updated, // can look at the “name”, “address” and “city” now } x.onActChange = function(str) { // Shared Object has been updated // can look at the “account” property now } SharedObject.
Description Event handler; reports errors, warnings, and status messages associated with either a local instance of a shared object or a persistent shared object. Example The following example defines an onStatus event handler for the shared object soInstance: soInstance = SharedObject.get("foo", true); soInstance.onStatus = function(infoObj){ //Handle SO status messages. }; SharedObject.onSync Availability Flash Communication Server MX 1.0. Usage mySO.
Proxied shared objects Code Meaning success A server change of the shared object was accepted. reject A server change of the shared object was rejected. The value on the remote instance was not changed. change A property was changed by another subscriber. delete A property was deleted. This notification can occur when a server deletes a shared object or if another subscriber deletes a property. clear All the properties of a shared object are deleted.
Example The following example creates a function that is invoked whenever a property of the shared object so changes: // Create a new NetConnection object. nc = new NetConnection(); nc.connect("rtmp://server1.xyx.com/myApp"); // Create the shared object. so = SharedObject.get("MasterUserList", true, nc); // The list parameter is an array of objects containing information // about successfully of unsuccessfully changed properties // from the last time onSync() was called. so.
Returns Nothing. Description Method; causes the server to purge all deleted properties that are older than the specified version. Although you can also accomplish this task by setting the SharedObject.resyncDepth property, the SharedObject.purge() method gives the script more control over which properties to delete. Example The following example deletes all the properties of the myShared shared object that are older than the value of myShared.version - 3: var myShared = SharedObject.
This method is useful when you add and delete many properties and you don’t want to send too many messages to the Flash client. Suppose a client is connected to a shared object that has 12 properties and then disconnects. After that client disconnects, other clients that are connected to the shared object delete 20 properties and add 10 properties. When the client reconnects, it could, for example, receive a delete message for the 10 properties it previously had and then a change message on two properties.
Example The following example calls the SharedObject.send() method to execute the doSomething() method in the client-side ActionScript and passes doSomething() the string "this is a test": var myShared = SharedObject.get("foo", true); myShared.send("doSomething", "this is a test"); The following example is the client-side ActionScript code that defines the doSomething method: connection = new NetConnection(); connection.connect("rtmp://www.macromedia.com/someApp"); var x = SharedObject.
A shared object property can be modified by a client between successive calls to SharedObject.getProperty() and SharedObject.setProperty(). If you want to preserve transactional integrity, call the SharedObject.lock() method before modifying the shared object; make sure to call SharedObject.unlock() when you finish making modifications. If you call SharedObject.setProperty() without first calling SharedObject.
Returns An integer indicating the number of properties. Description Method; returns the total number of valid properties in a shared object. Example The following example gets the number of properties of a shared object and assigns that number to the variable len: var myShared = SharedObject.get("foo", true); var len = myShared.size(); SharedObject.unlock() Availability Flash Communication Server MX 1.0. Usage mySO.unlock() Parameters None.
See also SharedObject.lock() SharedObject.version Availability Flash Communication Server MX 1.0. Usage mySO.version Description Property (read-only); the current version number of the shared object. Changes made to the shared object either by the Flash Player client or by the server-side script using the SharedObject.setProperty() method increment the value of the version property. SOAPCall class Availability Flash Media Server 2.
SOAPCall.onFault Availability Flash Media Server 2. Usage mySOAPCall.onFault(fault) Parameters The fault parameter is an object version of an XML SOAP Fault (see “SOAPFault class” on page 142). fault Returns Nothing. Description Event handler; invoked when a method has failed and returned an error. SOAPCall.onResult Availability Flash Media Server 2. Usage mySOAPCall.onResult(result){} Parameters The decoded ActionScript object returned by the operation (if any).
SOAPCall.request Availability Flash Media Server 2. Usage mySOAPCall.request Description Property; an XML object that represents the current SOAP request. SOAPCall.response Availability Flash Media Server 2. Usage mySOAPCall.response Description Property; an XML object that represents the most recent SOAP response. SOAPFault class Availability Flash Media Server 2. The SOAPFault class is the object type of the error object returned to WebService.onFault and SOAPCall.onFault functions.
Property Description SOAPFault.faultcode A string indicating the short standard qualified name describing the error. SOAPFault.faultstring A string indicating the human-readable description of the error. SOAPFault.detail Availability Flash Media Server 2. Usage mySOAPFault.detail Description Property; a string indicating the application-specific information associated with the error, such as a stack trace or other info returned by the web service engine. SOAPFault.
SOAPFault.faultstring Availability Flash Media Server 2. Usage mySOAPFault.faultstring Description Property; a string indicating the human-readable description of the error. Example The following example shows the fault code in a text field if the Web Service Definition Language (WSDL) fails to load: // Prepare the WSDL location: var wsdlURI = "http://www.flash-db.com/services/ws/companyInfo.
You can use the properties and methods of the Stream class to shuffle streams in a playlist, pull streams from other servers, and play and record streams. You can also use the Stream class to play MP3 files over a stream, as well as ID3 tags associated with MP3 files. You can create other Stream properties of any legal ActionScript type, including references to other ActionScript objects, for a particular instance of the Stream class.
Event handler summary for the Stream class Event handler Description Stream.onStatus Called when there is a change in status. Stream.bufferTime Availability Flash Communication Server MX 1.0. Usage myStream.bufferTime Description Property (read-only); indicates how long to buffer messages before a stream plays. This property applies only when playing a stream from a remote server or when playing a recorded stream locally. To set this property use Stream.setBuffertime.
Example The following example deletes a recorded stream called foo.flv. Before the stream is deleted, the example defines an onStatus handler that uses two information object error codes, NetStream.Clear.Success and NetStream.Clear.Failed, to send status messages to the application log file and Application inspector. s = Stream.get("foo"); if (s){ s.onStatus = function(info){ if(info.code == "NetStream.Clear.Success"){ trace("Stream cleared successfully."); } if(info.code == "NetStream.Clear.
It is highly recommended that you call flush() on a stream that contains only data. Synchronization problems can occur if you call the flush() method on a stream that contains data and either audio, video, or both. Example The following example flushes the myStream stream: // Setup the server stream application.myStream = Stream.get("foo"); if (application.myStream){ application.myStream.record(); application.myStream.send("test", "hello world"); application.myStream.flush(); } Stream.
Stream.length() Availability Flash Communication Server MX 1.0. Usage myStream.length(name[, virtualKey]) Parameters Name of a recorded stream (FLV) file or MP3 file. To get the length of an MP3 file, precede the name of the file with mp3: (for example, "mp3:beethoven"). name A string indicating a key value.
Stream.name Availability Flash Communication Server MX 1.0. Usage myStream.name Description Property (read-only); contains a unique string associated with a live stream. You can also use this as an index to find a stream within an application. Example The following function, getStreamName, takes a stream reference as an argument, myStream, and returns the name of the stream associated with it: function getStreamName (myStream) { return myStream.name; } Stream.
Example The following example defines a function that executes whenever the Stream.onStatus event is invoked: s = Stream.get("foo"); s.onStatus = function(info){ // Insert code here. }; Stream.play() Availability Flash Communication Server MX 1.0. Usage myStream.play(streamName, [startTime, length, reset, remoteConnection, virtualKey]) Parameters streamName The name of any published live stream, recorded stream (FLV file), or MP3 file.
length The length of play, in seconds. For a live stream, a value of -1 plays the stream as long as the stream exists. Any positive value plays the stream for the corresponding number of seconds. For a recorded stream, a value of -1 plays the entire file, and a value of 0 returns the first video frame. Any positive number plays the stream for the corresponding number of seconds. By default, the value is -1. This is an optional parameter. A Boolean value, or number, that flushes the playing stream.
Description Method; controls the data source of a stream with an optional start time, duration, and reset flag to flush any previously playing stream. The Stream.play() method also has a parameter that lets you reference a NetConnection object to play a stream from another server. The Stream.play() method allows you to do the following: ■ Chain streams between servers. ■ Create a hub to switch between live streams and recorded streams. ■ Combine different steams into a recorded stream.
Example The following example shows how streams can be chained between servers: application.myRemoteConn = new NetConnection(); application.myRemoteConn.onStatus = function(info){ trace("Connection to remote server status " + info.code + "\n"); // Tell all the clients. for (var i = 0; i < application.clients.length; i++){ application.clients[i].call("onServerStatus", null, info.code, info.description); } }; // Use the NetConnection object to connect to a remote server. application.myRemoteConn.
The following example creates a playlist of three MP3 files (beethoven.mp3, mozart.mp3, and chopin.mp3) and plays each file in turn over the live stream foo: application.myStream = Stream.get("foo"); if(application.myStream) { application.myStream.play("mp3:beethoven", 0); application.myStream.play("mp3:mozart", 0, false); application.myStream.play("mp3:chopin.mp3", 0, false); } In the following example, data messages in the recorded stream file log.
Example The following example opens a stream s and, when it is open, plays sample and records it. Because no value is passed to the record method, the default value, record, is passed. // Start recording. s = Stream.get("foo"); if (s){ s.play("sample"); s.record(); } // Stop recording. s = Stream.get("foo"); if (s){ s.record(false); } Stream.send() Availability Flash Communication Server MX 1.0. Usage myStream.send(handlerName, [p1, ...
Description Method; sends a message to all clients subscribing to the stream and the message is processed by the handler specified on the client. Because the server has higher priority than the clients, the server can still send a message on a stream owned by a client. Unlike the Stream.play() method, the server does not need to take ownership of a stream from the client in order to send a message. After send() is called, the client still owns the stream as a publisher.
Stream.setVirtualPath() Availability Flash Media Server 2. Usage myStream.setVirtualPath(virtualPath, directory, virtualKey) Parameters virtualPath A string indicating the virtual directory path of a stream. If the stream is not located in the virtual path, the default virtual directory path is searched. strDirectory virtualKey A string indicating the physical directory in which to store streams. A string that sets or removes the key value for each virtual path entry. Returns Nothing.
The following example shows the VirtualKeys section from the vhost.xml file in which the virtual keys can be mapped to a range of Flash Player versions: By default, there are no values in the key tags. To implement this feature, you must add the key values, either directly in the vhost.xml file, or with the setVirtualPath() method.
Example The following code sets the virtual key to B, the virtual path to /foo, and the physical directory to c:\streams\on2: myStream.setVirtualPath("B", "/foo", "c:\streams\on2"); Stream.size() Availability Flash Media Server 2. Usage Stream.size(name[, virtualKey]) Parameters A string indicating the name of a stream. You can use the format tag in the name parameter to specify the type. name virtualKey A string indicating a key value.
function onProcessCmd(cmd){ // Insert code here... var streamSize = Stream.size("mp3:foo" ); trace("Size: " + streamSize + "\n"); } Stream.syncWrite Availability Flash Media Server 2. Usage myStream.syncWrite Description Property; a Boolean value that controls when a stream writes the contents of the buffer to a FLV file when the stream is recording. When syncWrite is true, all the messages that pass through the stream are flushed to the FLV file immediately.
Parameters expression Any valid ActionScript expression. Returns Nothing. Description Method (global); evaluates an expression and displays the value. The expression appears in the Console window when the server is running in console mode; the expression is also published to the logs/application appname stream, which is available in the management console or in the Application inspector. The values in the trace expression are converted to strings if possible before they are output.
3. (Optional) Handle the WSDL parsing and web service instantiation event through the WebService.onLoad handler: // Handle the WSDL loading event. stockService.onLoad = function(wsdl){ wsdlField.text = wsdl; } 4. (Optional) Handle the fault if the WSDL doesn’t load: // If the WSDL fails to load the onFault event is fired. stockService.onFault = function(fault){ wsdlField.text = fault.faultstring; } 5.
Constructor for the WebService class Availability Flash Media Server 2. Usage new WebService(wsdlURI) Parameters A string specifying the URL of a WSDL URL. wsdlURL Returns A WebService object. Description Constructor; creates a new WebService object. You must use the constructor to create a WebService object before you call any of the WebService class methods.
Example The following example displays the fault code in a text field if the WSDL fails to load and the onFault event fires: // Prepare the WSDL location: var wsdlURI = "http://www.flash-db.com/services/ws/companyInfo.wsdl"; // Instantiate the web service object using the WSDL location: stockService = new WebService(wsdlURI); // Handle the WSDL parsing and web service instantiation event. stockService.onLoad = function(wsdl){ wsdlField.
Example In the following example, the onLoad event is used to handle the WSDL parsing: // Prepare the WSDL location: var wsdlURI = "http://www.flash-db.com/services/ws/companyInfo.wsdl"; // Instantiate the web service object using the WSDL location: stockService = new WebService(wsdlURI); // Handle the WSDL parsing and web service instantiation event. stockService.onLoad = function(wsdl){ wsdlField.text = wsdl; } XML class Availability Flash Media Server 2.
Property summary for the XML class Property Description XML.attributes An object that contains all the attributes of the specified XML object. XML.childNodes Read-only; an array of the specified XML object’s children. Each element in the array is a reference to an XML object that represents a child node. XML.contentType The MIME type transmitted to the server. XML.docTypeDecl Sets and returns information about an XML document’s DOCTYPE declaration. XML.
Method summary for the XML class Method Description XML.addRequestHeader() Adds or changes HTTP headers for POST operations. XML.appendChild() Appends a node to the end of the specified object’s child list. XML.cloneNode() Clones the specified node, and optionally, recursively clones all children. XML.createElement() Creates a new XML element. XML.createTextNode() Creates a new XML text node. XML.getBytesLoaded() Returns the number of bytes loaded for the specified XML document. XML.
Event handler summary for the XML class Event handler Description XML.onData Invoked when XML text has been completely downloaded from the server or when an error occurs downloading XML text from a server. XML.onHTTPStatus Invoked when Flash Media Server receives an HTTP status code from the server. This handler lets you capture and act on HTTP status codes. XML.onLoad Returns a Boolean value indicating whether the XML object was successfully loaded with XML.load() or XML.sendAndLoad().
Description Constructor; creates a new XML object. You must use the constructor to create an XML object before you call any of the XML class methods. N OT E Use the createElement() and createTextNode() methods to add elements and text nodes to an XML document tree.
Description Method; adds or changes HTTP request headers (such as Content-Type or SOAPAction) sent with POST actions. In the first usage, you pass two strings, headerName and headerValue, to the method. In the second usage, you pass an array of strings, alternating header names, and header values. If multiple calls are made to set the same header name, each successive value replaces the value set in the previous call.
Description Method; appends the specified node to the XML object’s child list. This method operates directly on the node referenced by the childNode parameter; it does not append a copy of the node. If the node to be appended already exists in another tree structure, appending the node to the new location will remove it from its current location.
XML.attributes Availability Flash Media Server 2. Usage my_xml.attributes Description Property; an object that contains all the attributes of the specified XML object. Associative arrays use keys as indexes, not ordinal integer indexes used by regular arrays. In the XML.attributes associative array, the key index is a string representing the name of the attribute. The value associated with that key index is the string value associated with that attribute.
XML.childNodes Availability Flash Media Server 2. Usage my_xml.childNodes Description Property (read-only); an array of the specified XML object’s children. Each element in the array is a reference to an XML object that represents a child node. This is a read-only property and cannot be used to manipulate child nodes. Use the XML.appendChild(), XML.insertBefore(), and XML.removeNode() methods to manipulate child nodes. This property is undefined for text nodes (nodeType == 3).
// Create another array and use the child nodes to populate it. var secondArray = rootNode.childNodes; trace(secondArray); // Output: ,, NO TE In Flash Media Server, the output of trace() statements appears in the application log file and Application inspector. See also XML.nodeType XML.cloneNode() Availability Flash Media Server 2. Usage my_xml.
Example The following example shows how to use the XML.cloneNode() method to create a copy of a node: // Create a new XML document. var doc = new XML(); // Create a root node. var rootNode = doc.createElement("rootNode"); // Create three child nodes. var oldest = doc.createElement("oldest"); var middle = doc.createElement("middle"); var youngest = doc.createElement("youngest"); // Add the rootNode as the root of the XML document tree. doc.
// // // // // // // NO TE In Flash Media Server, the output of trace() statements appears in the application log file and Application inspector. XML.contentType Availability Flash Media Server 2. Usage my_xml.contentType Description Property; the MIME content type that is sent to the server when you call the XML.send() or XML.sendAndLoad() method.
XML.createElement() Availability Flash Media Server 2. Usage my_xml.createElement(name) Parameters name The tag name of the XML element being created. Returns An XML node; an XML element. Description Method; creates a new XML element with the name specified in the name parameter. The new element initially has no parent, children, or siblings. The method returns a reference to the newly created XML object that represents the element. This method and the XML.
XML.createTextNode() Availability Flash Media Server 2. Usage my_xml.createTextNode(text) Parameters text A string; the text used to create the new text node. Returns An XML node. Description Method; creates a new XML text node with the specified text. The new node initially has no parent, and text nodes cannot have children or siblings. This method returns a reference to the XML object that represents the new text node. This method and the XML.
trace(doc); // Output (with line breaks added between tags): // // textNode1 // textNode2 // NO T E In Flash Media Server, the output of trace() statements appears in the application log file and Application inspector. See also XML.createElement() XML.docTypeDecl Availability Flash Media Server 2. Usage my_xml.docTypeDecl Description Property; specifies information about the XML document’s DOCTYPE declaration.
XML.firstChild Availability Flash Media Server 2. Usage my_xml.firstChild Description Property (read-only); evaluates the specified XML object and references the first child in the parent node’s child list. This property is null if the node does not have children. This property is null if the node is a text node. This is a read-only property and cannot be used to manipulate child nodes; use the appendChild(), insertBefore(), and removeNode() methods to manipulate child nodes.
// // N OT E In Flash Media Server, the output of trace() statements appears in the application log file and Application inspector. See also XML.appendChild(), XML.insertBefore(), XML.removeNode() XML.getBytesLoaded() Availability Flash Media Server 2. Usage my_xml.getBytesLoaded() Parameters None. Returns An integer that indicates the number of bytes loaded. Description Method; returns the number of bytes loaded (streamed) for the XML document.
Returns An integer. Description Method; returns the size of the XML document in bytes. Example See the example for XML.getBytesLoaded() on page 182. See also XML.getBytesLoaded() XML.getNamespaceForPrefix() Availability Flash Media Server 2. Usage my_xml.getNamespaceForPrefix(prefix) Parameters prefix A string; the prefix for which the method returns the associated namespace. Returns A String; the namespace that is associated with the specified prefix.
Example The following example creates a very simple XML object and outputs the result of a call to getNamespaceForPrefix(): function createXML() { var str = "" + "" + "" + "" + ""; return new XML(str).firstChild; } var xml = createXML(); trace(xml.getNamespaceForPrefix("exu")); // output: http://www.example.com/ util trace(xml.getNamespaceForPrefix("")); // output: null See also XML.
Example The following example creates a very simple XML object and outputs the result of a call to the getPrefixForNamespace() method. The Outer XML node, which is represented by the xmlDoc variable, defines a namespace URI and assigns it to the exu prefix. Calling the getPrefixForNamespace() method with the defined namespace URI ("http:// www.example.com/util") returns the prefix exu, but calling this method with an undefined URI ("http://www.example.com/other") returns null.
XML.hasChildNodes() Availability Flash Media Server 2. Usage my_xml.hasChildNodes() Parameters None. Returns A Boolean value. Description Method; returns true if the specified XML object has child nodes; false otherwise. Example The following example creates a new XML packet. If the root node has child nodes, the code loops over each child node to display the name and value of the node. var my_xml = new XML("hank rudolph"); if (my_xml.
XML.ignoreWhite Availability Flash Media Server 2. Usage my_xml.ignoreWhite XML.prototype.ignoreWhite Parameters boolean A Boolean value. Description Property; the default setting is false. When set to true, text nodes that contain only white space are discarded during the parsing process. Text nodes with leading or trailing white spaces are unaffected. Usage 1: You can set the ignoreWhite property for individual XML objects, as shown in the following code: my_xml.
Create a new Flash document named flooring.fla and save it to the same directory as the XML file. Place the following code into the main timeline: // Create a new XML object. var flooring = new XML(); // Set the ignoreWhite property to true (default value is false). flooring.ignoreWhite = true; // After loading is complete, trace the XML object. flooring.onLoad = function(success) { trace(flooring); } // Load the XML into the flooring object. flooring.load("flooring.
XML.insertBefore() Availability Flash Media Server 2. Usage my_xml.insertBefore(childNode, beforeNode) Parameters childNode The XMLNode object to be inserted. beforeNode The XMLNode object before the insertion point for the childNode node. Returns Nothing. Description Method; inserts a new child node into the XML object’s child list, before the beforeNode node. If beforeNode is not a child of my_xml, the insertion fails. Example The following example is an excerpt from the XML.
Example The following example uses the XML.lastChild property to iterate through the child nodes of an XMLNode object, starting with the last item in the node’s child list and ending with the first child of the node’s child list: // Create a new XML document. var doc = new XML(); // Create a root node. var rootNode = doc.createElement("rootNode"); // Create three child nodes. var oldest = doc.createElement("oldest"); var middle = doc.createElement("middle"); var youngest = doc.
The following example creates a new XML packet and uses the XML.lastChild property to iterate through the child nodes of the root node: // Create a new XML document. var doc = new XML(""); var rootNode = doc.firstChild; // Use lastChild to iterate through the child nodes of rootNode. for (var aNode = rootNode.lastChild; aNode != null; aNode=aNode.
Description Method; loads an XML document from the specified URL, and replaces the contents of the specified XML object with the downloaded XML data. The URL is relative and is called using HTTP. The load process is asynchronous; it does not finish immediately after the load() method is executed. When the load() method is executed, the XML object property loaded is set to false. When the XML data finishes downloading, the loaded property is set to true, and the onLoad event handler is invoked.
XML.loaded Availability Flash Media Server 2. Usage my_xml.loaded Description Property; a Boolean value that is true if the document-loading process initiated by the XML.load() call completed successfully; false otherwise. Example The following example uses the XML.loaded property in a simple script: var my_xml = new XML(); my_xml.ignoreWhite = true; my_xml.onLoad = function(success) { trace("success: "+success); trace("loaded: "+my_xml.loaded); trace("status: "+my_xml.status); }; my_xml.
XML.localName Availability Flash Media Server 2. Usage my_xml.localName Description Property (read-only); the local name portion of the XML node's name. This is the element name without the namespace prefix. For example, the node bob@example.com has the local name “mailbox”, and the prefix “contact”, which comprise the full element name “contact.mailbox”. You can access the namespace prefix via the XML.prefix property of the XML node object. The XML.
See also XML.nodeName, XML.prefix XML.namespaceURI Availability Flash Media Server 2. Usage my_xml.namespaceURI Description Property (read-only); if the XML node has a prefix, namespaceURI is the value of the xmlns declaration for that prefix (the URI), which is typically called the namespace URI. The xmlns declaration is in the current node or in a node higher in the XML hierarchy.
The source for the server-side ASC file contains the following script (note the comments for the Output strings). For tempNode, which represents the w:GetTemperature node, the value of namespaceURI is defined in the soap:Body tag. For soapBodyNode, which represents the soap:Body node, the value of namespaceURI is determined by the definition of the soap prefix in the node above it, rather than the definition of the w prefix that the soap:Body node contains. var xmlDoc = new XML(); xmlDoc.load("SoapSample.
trace("rootNode Node namespaceURI: " + rootNode.namespaceURI); // Output: [empty string] var simpleNode = xmlDoc.childNodes[0].childNodes[0]; trace("simpleNode Node namespaceURI: " + simpleNode.namespaceURI); // Output: ... http://www.w3.org/2001/12/soap-envelope var innerNode = xmlDoc.childNodes[0].childNodes[0].childNodes[0]; trace("innerNode Node namespaceURI: " + innerNode.namespaceURI); // Output: ... http://www.w3.org/2001/12/soap-envelope } XML.nextSibling Availability Flash Media Server 2.
XML.nodeName Availability Flash Media Server 2. Usage my_xml.nodeName Description Property; a string representing the node name of the XML object. If the XML object is an XML element (nodeType==1), nodeName is the name of the tag that represents the node in the XML file. For example, TITLE is the nodeName of an HTML TITLE tag. If the XML object is a text node (nodeType==3), nodeName is null.
The following example creates a new XML packet. If the root node has child nodes, the code loops over each child node to display the name and value of the node. Add the following ActionScript to your ASC file: var my_xml = new XML("hank rudolph"); if (my_xml.firstChild.hasChildNodes()) { // Use firstChild to iterate through the child nodes of rootNode. for (var aNode = my_xml.firstChild.firstChild; aNode != null; aNode=aNode.nextSibling) { if (aNode.
Integer value Defined constant 4 CDATA_SECTION_NODE 5 ENTITY_REFERENCE_NODE 6 ENTITY_NODE 7 PROCESSING_INSTRUCTION_NODE 8 COMMENT_NODE 9 DOCUMENT_NODE 10 DOCUMENT_TYPE_NODE 11 DOCUMENT_FRAGMENT_NODE 12 NOTATION_NODE In Flash Player, the built-in XML class supports only 1 (ELEMENT_NODE) and 3 (TEXT_NODE). Example The following example creates an element node and a text node and checks the node type of each: // Create an XML document.
See also XML.nodeValue XML.nodeValue Availability Flash Media Server 2. Usage my_xml.nodeValue Description Property; the node value of the XML object. If the XML object is a text node, the nodeType is 3, and the nodeValue is the text of the node. If the XML object is an XML element (nodeType is 1), nodeValue is null and read-only. Example The following example creates an element node and a text node and checks the node value of each: // Create an XML document.
N O TE In Flash Media Server, the output of trace() statements appears in the application log file and Application inspector. The following example creates and parses an XML packet. The code loops through each child node, and displays the node value using the firstChild property and firstChild.nodeValue. var my_xml = new XML("morton good&evil"); trace("using firstChild:"); for (var i = 0; i
Returns Nothing. Description Event handler; invoked when XML text has been completely downloaded from the server or when an error occurs when XML text downloads from a server. This handler is invoked before the XML is parsed, and you can use it to call a custom parsing routine instead of using the Flash XML parser. The src parameter is a string that contains XML text downloaded from the server, unless an error occurs during the download. In this situation, the src parameter is undefined.
Description Event handler; invoked when Flash Media Server receives an HTTP status code from the server. This handler lets you capture and act on HTTP status codes. The onHTTPStatus handler is invoked before onData, which triggers calls to onLoad with a value of undefined if the load fails. After onHTTPStatus is triggered, onData is always triggered, whether or not you override onHTTPStatus.
if(src != undefined) { this.parseXML(src); this.loaded = true; this.onLoad(true); } else { this.onLoad(false); } } myXml.onLoad = function(success) { } myXml.load("http://weblogs.macromedia.com/mxna/xml/ rss.cfm?query=byMostRecent&languages=1"); See also LoadVars.onHTTPStatus, XML.send(), XML.sendAndLoad() XML.onLoad Availability Flash Media Server 2. Usage my_xml.onLoad = function (success) {} Parameters success A Boolean value that is true if the XML object successfully loads with a or XML.
Example The following example includes ActionScript for a simple e-commerce storefront application. The sendAndLoad() method transmits an XML element that contains the user’s name and password and uses an XML.onLoad handler to process the reply from the server. var login_str = ""; var my_xml = new XML(login_str); var myLoginReply_xml = new XML(); myLoginReply_xml.ignoreWhite = true; myLoginReply_xml.
Example The following example creates an XML packet and writes the parent node of the username node to the log file: var my_xml = new XML("morton good&evil"); // The first child is the node. var rootNode = my_xml.firstChild; // The first child of the root is the node. var targetNode = rootNode.firstChild; trace("the parent node of '"+targetNode.nodeName+"' is: "+targetNode.parentNode.
Description Method; parses the XML text specified in the source parameter and populates the specified XML object with the resulting XML tree. Any existing trees in the XML object are discarded. Example The following example creates and parses an XML packet: var xml_str = " San Francisco" // Defining the XML source within the XML constructor: var my1_xml = new XML(xml_str); trace(my1_xml.firstChild.attributes.
Example A directory contains a server-side script file and an XML file. The XML file, named "SoapSample.xml" contains the following: PAGE 210Example The following example is an excerpt from the example for the XML.lastChild property and shows how you can use the XML.previousSibling property to loop through an XMLNode object’s child nodes: for (var aNode = rootNode.lastChild; aNode != null; aNode = aNode.previousSibling) { trace(aNode); } NO T E In Flash Media Server, the output of trace() statements appears in the application log file and Application inspector. See also XML.appendChild(), XML.insertBefore(), XML.removeNode() XML.
Example The following example creates an XML packet and then deletes the specified XML object and its descendant nodes: var xml_str = " San Francisco"; var my_xml = new XML(xml_str); var cityNode = my_xml.firstChild.firstChild; trace("before XML.removeNode():\n"+my_xml); cityNode.removeNode(); trace(""); trace("after XML.removeNode():\n"+my_xml); /* output (line breaks added for clarity): before XML.
Returns Nothing. Description Method; encodes the specified XML object into an XML document and sends it to the specified URL using the POST method in a browser. The Flash test environment uses only the GET method. Example The following example defines an XML packet and sets the content type for the XML object. The data is then sent to a server and writes the result in a File object. var my_xml = new XML("Ernie 13045"); my_xml.
When sendAndLoad() is executed, the XML object property loaded is set to false. When the XML data finishes downloading, the loaded property is set to true if the data successfully loads and the onLoad event handler is invoked. The XML data is not parsed until it is completely downloaded. If the XML object previously contained any XML trees, they are discarded. Example The following example includes ActionScript for a simple e-commerce storefront application. The XML.
XML.status Availability Flash Media Server 2. Usage my_xml.status Description Property; automatically sets and returns a numeric value that indicates whether an XML document was successfully parsed into an XML object. The following list contains the numeric status codes with descriptions: ■ 0 No error; parse was completed successfully. ■ -2 A CDATA section was not properly terminated. ■ -3 The XML declaration was not properly terminated. ■ -4 The DOCTYPE declaration was not properly terminated.
errorMessage = "A CDATA section was not properly terminated."; break; case -3 : errorMessage = "The XML declaration was not properly terminated."; break; case -4 : errorMessage = "The DOCTYPE declaration was not properly terminated."; break; case -5 : errorMessage = "A comment was not properly terminated."; break; case -6 : errorMessage = "An XML element was malformed."; break; case -7 : errorMessage = "Out of memory."; break; case -8 : errorMessage = "An attribute value was not properly terminated.
XML.toString() Availability Flash Media Server 2. Usage my_xml.toString() Parameters None. Returns A string. Description Method; evaluates the specified XML object, constructs a textual representation of the XML structure, including the node, children, and attributes, and returns the result as a string. For top-level XML objects (those created with the constructor), the XML.toString() method outputs the document’s XML declaration (stored in the XML.
XML.xmlDecl Availability Flash Media Server 2. Usage my_xml.xmlDecl Description Property; a string that specifies information about a document’s XML declaration. After the XML document is parsed into an XML object, this property is set to the text of the document’s XML declaration. This property is set using a string representation of the XML declaration, not an XMLNode object. If no XML declaration is encountered during a parse operation, the property is set to undefined.XML. The XML.
XMLSocket class Availability Flash Media Server 2. Description The XMLSocket class implements client sockets that let Flash Media Server communicate with a server 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.
Method summary for the XMLSocket class Method Description XMLSocket.close() Closes an open socket connection. XMLSocket.connect() Establishes a connection to the specified server. XMLSocket.send() Sends an XML object to the server. Event handler summary for the XMLSocket class Event handler Description XMLSocket.onClose Invoked when an XMLSocket connection is closed. XMLSocket.onConnect Invoked by Flash Media Server when a connection request initiated through XMLSocket.
For more information about the XMLStreams class, see “XMLStreams class” on page 227. Example The following example creates an XMLSocket object: var socket = new XMLSocket("flash"); The following example creates an XMLStreams object: var stream = new XMLSocket("stream"); XMLSocket.close() Availability Flash Media Server 2. Usage myXMLSocket.close() Parameters None. Returns Nothing. Description Method; closes the connection specified by the XMLSocket object.
XMLSocket.connect() Availability Flash Media Server 2. Usage myXMLSocket.connect(host, port) Parameters A string; a fully qualified DNS domain name or an IP address in the form aaa.bbb.ccc.ddd. You can also specify null to connect to the local host. host A number; the TCP port number on the host used to establish a connection. The port number must be 1024 or greater. port Returns A Boolean value; true if successful, false if not.
Example The following example uses XMLSocket.connect() to connect to the local host: var socket = new XMLSocket() socket.onConnect = function (success) { if (success) { trace ("Connection succeeded!") } else { trace ("Connection failed!") } } if (!socket.connect(null, 2000)) { trace ("Connection failed!") } N OT E In Flash Media Server, the output of trace() statements appears in the application log file and Application inspector. See also XMLSocket.onConnect XMLSocket.
Example The following example executes a trace() statement if an open connection is closed by the server: var socket = new XMLSocket(); socket.connect(null, 2000); socket.onClose = function () { trace("Connection to server lost."); } NO T E In Flash Media Server, the output of trace() statements appears in the application log file and Application inspector. See also XMLSocket.onConnect XMLSocket.onConnect Availability Flash Media Server 2. Usage myXMLSocket.
Example The following example defines a function for the onConnect handler: socket = new XMLSocket(); socket.onConnect = myOnConnect; socket.connect(null,2000); function myOnConnect(success) { if (success) { trace("Connection success") } else { trace("Connection failed") } } See also XMLSocket.connect() XMLSocket.onData Availability Flash Media Server 2. Usage myXMLSocket.onData = function(src) {} Parameters src A string containing the data sent by the server. Returns Nothing.
Example In the following example, the src parameter is a string containing XML text downloaded from the server. The zero (0) byte terminator is not included in the string. XMLSocket.prototype.onData = function (src) { this.onXML(new XML(src)); } XMLSocket.onXML Availability Flash Media Server 2. Usage myXMLSocket.onXML = function(object) {} Parameters object An XML object that contains a parsed XML document received from a server. Returns Nothing.
The following displayMessage() function is assumed to be a user-defined function that shows the message that the user receives: socket.onXML = function (doc) { var e = doc.firstChild; if (e != null && e.nodeName == "MESSAGE") { displayMessage(e.attributes.user, e.attributes.text); } } XMLSocket.send() Availability Flash Media Server 2. Usage myXMLSocket.send(object) Parameters object An XML object or other data to transmit to the server. Returns Nothing.
See also XMLSocket.connect() XMLStreams class Availability Flash Media Server 2. Description The XMLStreams class is a variation of the XMLSocket class—it has all the same methods, properties, and events, but it transmits and receives data in fragments. To create an XMLStreams object, use the XMLSocket constructor and pass "stream" as the parameter. See “Constructor for the XMLSocket class” on page 219.
Server-Side ActionScript Language Reference
APPENDIX A A Server-Side Information Objects The Application, NetConnection, and Stream classes provide an onStatus event handler that uses an information object for providing information, status, or error messages. To respond to this event handler, you must create a function to process the information object, and you must know the format and contents of the information object returned. You can define the following global function at the top of your main.
Application information objects The following table lists the information objects for the Application object. Code Level Meaning Application.Script.Error Error The ActionScript engine has encountered a runtime error. In addition to the standard infoObject properties, the following properties are set: filename: name of the offending ASC file. lineno: line number where the error occurred. linebuf: source code of the offending line. Application.Script.
NetConnection information objects The NetConnection class has the same information objects as the client-side NetConnection class. Code Level Meaning NetConnection.Call.Failed Error The NetConnection.call method was not able to invoke the server-side method or command.* NetConnection.Connect.AppShutdown Error The application has been shut down (for example, if the application is out of memory resources and must shut down to prevent the server from crashing) or the server has shut down.
Stream information objects The information objects of the Stream class are similar to those of the client-side NetStream class. Code Level Meaning NetStream.Clear.Success Status A recorded stream was deleted successfully. NetStream.Clear.Failed Error A recorded stream failed to delete. NetStream.Publish.Start Status An attempt to publish was successful. NetStream.Publish.BadName Error An attempt was made to publish a stream that is already being published by someone else. NetStream.
† This information object also has a details property, which is a string that provides the name of the streams being played. This is useful for multiple plays. The details property shows the name of the stream when switching from one element in the playlist to the next element. *** By default, outgoing messages are monitored at 5 second intervals; if data is behind, the client is notified within 5 seconds. The interval for sampling can be configured in the Application.xml file in the Client tag.
Server-Side Information Objects