User Guide

284 Chapter 11: Working with External Data
Using the XMLSocket class
ActionScript provides a built-in XMLSocket class, which lets you open a continuous connection
with a server. A socket connection lets the server publish, or push, information to the client as
soon as that information is available. Without a continuous connection, the server must wait for
an HTTP request. This open connection removes latency issues and is commonly used for real-
time applications such as chats. The data is sent over the socket connection as one string and
should be formatted as XML. You can use the XML class to structure the data.
To create a socket connection, you must create a server-side application to wait for the socket
connection request and send a response to the SWF file. This type of server-side application can
be written in a programming language such as Java.
Note: The XMLSocket class cannot tunnel through firewalls automatically because, unlike RTMP
protocol, XMLSocket has no HTTP tunneling capability. If you need to use HTTP tunneling, consider
using Flash Remoting or Flash Communication Server (which supports RTMP) instead.
You can use the connect() and send() methods of the XMLSocket class to transfer XML to and
from a server over a socket connection. The
connect() method establishes a socket connection
with a web server port. The
send() method passes an XML object to the server specified in the
socket connection.
When you invoke the
connect() method, Flash Player opens a TCP/IP connection to the server
and keeps that connection open until one of the following events happens:
The close() method of the XMLSocket class is called.
No more references to the XMLSocket object exist.
Flash Player exits.
The connection is broken (for example, the modem disconnects).
The following example creates an XML socket connection and sends data from the XML object
myXML. To understand the script, read the commented lines (indicated by the characters //):
//create XMLSocket object
var theSocket:XMLSocket = new XMLSocket();
//connect to a site on unused port above 1024 using connect() method
//enter localhost or 127.0.0.1 for local testing
//for live server enter your domain www.yourdomain.com
theSocket.connect("localhost", 12345);
//displays text regarding connection
theSocket.onConnect = function(myStatus) {
if (myStatus) {
conn_txt.text = "connection successful";
} else {
conn_txt.text = "no connection made";
}
};
//data to send
function sendData() {
var myXML:XML = new XML();
var mySend = myXML.createElement("thenode");
mySend.attributes.myData = "someData";
myXML.appendChild(mySend);