PackageTop Level
Classpublic class XMLSocket
InheritanceXMLSocket Inheritance Object

Player version: Flash Player 5

The XMLSocket class implements client sockets that let the computer running Flash Player communicate with a server computer identified by an IP address or domain name. The XMLSocket class is useful for client-server applications that require low latency, such as real-time chat systems. A traditional HTTP-based chat solution frequently polls the server and downloads new messages using an HTTP request. In contrast, an XMLSocket chat solution maintains an open connection to the server, which lets the server immediately send incoming messages without a request from the client. To use the XMLSocket class, the server computer must run a daemon that understands the protocol used by the XMLSocket class. The protocol is described in the following list:

Setting up a server to communicate with the XMLSocket object can be challenging. If your application does not require real-time interactivity, use the loadVariables() function, or Flash HTTP-based XML server connectivity (XML.load(), XML.sendAndLoad(), XML.send()), instead of the XMLSocket class.

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

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

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

For more information related to security, see the following:



Public Properties
 Property
  timeout : Number
The number of milliseconds to wait for a connection.
 Properties inherited from class Object
 __proto__, __resolve, constructor, prototype
Public Methods
 Method
  
Creates a new XMLSocket object.
  
close():Void
Closes the connection specified by XMLSocket object.
  
Establishes a connection to the specified Internet host using the specified TCP port, and returns true or false, depending on whether a connection is successfully established.
  
send(data:Object):Void
Converts the XML object or data specified in the object parameter to a string and transmits it to the server, followed by a zero (0) byte.
 Methods inherited from class Object
 addProperty, hasOwnProperty, isPropertyEnumerable, isPrototypeOf, registerClass, toString, unwatch, valueOf, watch
Events
 EventSummaryDefined by
  
onClose = function() {}
Invoked only when an open connection is closed by the server.XMLSocket
  
onConnect = function(success:Boolean) {}
Invoked by Flash Player when a connection request initiated through XMLSocket.connect() has succeeded or failed.XMLSocket
  
onData = function(src:String) {}
Invoked when a message has been downloaded from the server, terminated by a zero (0) byte.XMLSocket
  
onXML = function(src:XML) {}
Invoked by Flash Player when the specified XML object containing an XML document arrives over an open XMLSocket connection.XMLSocket
Property detail
timeoutproperty
public var timeout:Number

Language version: ActionScript 2.0
Player version: Flash Player 10

The number of milliseconds to wait for a connection.

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

Constructor detail
XMLSocket()constructor
public function XMLSocket()

Player version: Flash Player 5

Creates a new XMLSocket object. The XMLSocket object is not initially connected to any server. You must call XMLSocket.connect() to connect the object to a server.


Example
The following example creates an XMLSocket object:
var socket:XMLSocket = new XMLSocket();

Method detail
close()method
public function close():Void

Player version: Flash Player 5

Closes the connection specified by XMLSocket object.

See also


Example
The following simple example creates an XMLSocket object, attempts to connect to the server, and then closes the connection.
var socket:XMLSocket = new XMLSocket();
socket.connect(null, 2000);
socket.close();

connect()method 
public function connect(host:String, port:Number):Boolean

Player version: Flash Player 5 — Behavior changed in Flash Player 7 and Flash Player 9.

Establishes a connection to the specified Internet host using the specified TCP port, and returns true or false, depending on whether a connection is successfully established. If you do not know the port number of your Internet host computer, contact your network administrator.

If you specify null for the host parameter, the host contacted is the one where the SWF file calling XMLSocket.connect() resides. For example, if the SWF file was downloaded from www.yoursite.com, specifying null for the host parameter is the same as entering the IP address for www.yoursite.com.

When load() 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. The XML data is not parsed until it is completely downloaded. If the XML object previously contained any XML trees, they are discarded.

If XMLSocket.connect() returns a value of true, the initial stage of the connection process is successful; later, the XMLSocket.onConnect method is invoked to determine whether the final connection succeeded or failed. If XMLSocket.connect() returns false, a connection could not be established.

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

      rtmp://[2001:db8:ccc3:ffff:0:444d:555e:666f]:1935/test
      

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

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

For more information related to security, see the following:

Parameters
host:String — 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 host server on which the SWF file resides. If the SWF file issuing this call is running in a web browser, host must be in the same domain as the SWF file; for details, see the information about domain restrictions for SWF files in the main description of this method.
 
port:Number — A number; the TCP port number on the host used to establish a connection.

Returns
Booleantrue if the connection is successful; false otherwise.

See also


Example
The following example uses XMLSocket.connect() to connect to the host where the SWF file resides and uses trace to display the return value indicating the success or failure of the connection:
var socket:XMLSocket = new XMLSocket()
socket.onConnect = function (success:Boolean) {
    if (success) {
    trace ("Connection succeeded!")
    } else {
    trace ("Connection failed!")
    }
}
if (!socket.connect(null, 2000)) {
    trace ("Connection failed!")
}

send()method 
public function send(data:Object):Void

Player version: Flash Player 5

Converts the XML object or data specified in the object parameter to a string and transmits it to the server, followed by a zero (0) byte. If object is an XML object, the string is the XML textual representation of the XML object. The send operation is asynchronous; it returns immediately, but the data may be transmitted at a later time. The XMLSocket.send() method does not return a value indicating whether the data was successfully transmitted.

If the myXMLSocket object is not connected to the server (using XMLSocket.connect()), the XMLSocket.send() operation will fail.

Parameters
data:Object — An XML object or other data to transmit to the server.

See also


Example
The following example shows how you could specify a user name and password to send the XML object my_xml to the server:
var myXMLSocket:XMLSocket = new XMLSocket();
var my_xml:XML = new XML();
var myLogin:XMLNode = my_xml.createElement("login");
myLogin.attributes.username = usernameTextField;
myLogin.attributes.password = passwordTextField;
my_xml.appendChild(myLogin);
myXMLSocket.send(my_xml);

Event detail
onCloseevent handler

public onClose = function() {}

Player version: Flash Player 5

Invoked only when an open connection is closed by the server. The default implementation of this method performs no actions. To override the default implementation, you must assign a function containing custom actions.


Example
The following example executes a trace statement if an open connection is closed by the server:
var socket:XMLSocket = new XMLSocket();
socket.connect(null, 2000);
socket.onClose = function () {
    trace("Connection to server lost.");
}

See also

onConnectevent handler 

public onConnect = function(success:Boolean) {}

Player version: Flash Player 5

Invoked by Flash Player when a connection request initiated through XMLSocket.connect() has succeeded or failed. If the connection succeeded, the success parameter is true; otherwise the success parameter is false.

The default implementation of this method performs no actions. To override the default implementation, you must assign a function containing custom actions.

Parameters
success:Boolean — A Boolean value indicating whether a socket connection is successfully established (true or false).

Example
The following example illustrates the process of specifying a replacement function for the onConnect method in a simple chat application.

After creating the XMLSocket object using the constructor method, the script defines the custom function to be executed when the onConnect event handler is invoked. The function controls the screen to which users are taken, depending on whether a connection is successfully established. If the connection is successfully made, users are taken to the main chat screen on the frame labeled startChat. If the connection is not successful, users go to a screen with troubleshooting information on the frame labeled connectionFailed.

var socket:XMLSocket = new XMLSocket();
socket.onConnect = function (success) {
    if (success) {
        gotoAndPlay("startChat");
    } else {
        gotoAndStop("connectionFailed");
    }
}

Finally, the connection is initiated. If connect() returns false, the SWF file is sent directly to the frame labeled connectionFailed, and onConnect is never invoked. If connect() returns true, the SWF file jumps to a frame labeled waitForConnection, which is the "Please wait" screen. The SWF file remains on the waitForConnection frame until the onConnect handler is invoked, which happens at some point in the future depending on network latency.

if (!socket.connect(null, 2000)) {
    gotoAndStop("connectionFailed");
} else {
    gotoAndStop("waitForConnection");
}

See also

onDataevent handler 

public onData = function(src:String) {}

Player version: Flash Player 5

Invoked when a message has been downloaded from the server, terminated by a zero (0) byte. You can override XMLSocket.onData to intercept the data sent by the server without parsing it as XML. This is a useful if you're transmitting arbitrarily formatted data packets, and you'd prefer to manipulate the data directly when it arrives, rather than have Flash Player parse the data as XML.

By default, the XMLSocket.onData method invokes the XMLSocket.onXML method. If you override XMLSocket.onData with custom behavior, XMLSocket.onXML is not called unless you call it in your implementation of XMLSocket.onData.

Parameters
src:String — A string containing the data sent by the server.

Example
In this 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));
}

onXMLevent handler 

public onXML = function(src:XML) {}

Player version: Flash Player 5

Invoked by Flash Player when the specified XML object containing an XML document arrives over an open XMLSocket connection. An XMLSocket connection can be used to transfer an unlimited number of XML documents between the client and the server. Each document is terminated with a zero (0) byte. When Flash Player receives the zero byte, it parses all the XML received since the previous zero byte or since the connection was established if this is the first message received. Each batch of parsed XML is treated as a single XML document and passed to the onXML method.

The default implementation of this method performs no actions. To override the default implementation, you must assign a function containing actions that you define.

Parameters
src:XML — An XML object that contains a parsed XML document received from a server.

Example
The following function overrides the default implementation of the onXML method in a simple chat application. The function myOnXML instructs the chat application to recognize a single XML element, MESSAGE, in the following format.

      <MESSAGE user="John" text="Hello, my name is John!" />.
      

The following function displayMessage() is assumed to be a user-defined function that displays the message received by the user:

var socket:XMLSocket = new XMLSocket();
socket.onXML = function (doc) {
    var e = doc.firstChild;
    if (e != null && e.nodeName == "MESSAGE") {
        displayMessage(e.attributes.user, e.attributes.text);
    }
}

See also