Adobe® AIR® API Reference for HTML Developers
Home  |  Show Classes List |  Index  |  Appendixes

Language Reference only       
XMLSocket 
3D:
Context3D
Context3DBlendFactor
Context3DClearMask
Context3DCompareMode
Context3DProgramType
Context3DRenderMode
Context3DStencilAction
Context3DTextureFormat
Context3DTriangleFace
Context3DVertexBufferFormat
CubeTexture
IndexBuffer3D
Program3D
Stage3D
Texture
VertexBuffer3D
Air.net:
ServiceMonitor
SocketMonitor
URLMonitor
Air.update:
ApplicationUpdater
ApplicationUpdaterUI
DownloadErrorEvent
StatusFileUpdateErrorEvent
StatusFileUpdateEvent
StatusUpdateErrorEvent
StatusUpdateEvent
UpdateEvent
Data:
EncryptedLocalStore
SQLCollationType
SQLColumnNameStyle
SQLColumnSchema
SQLConnection
SQLError
SQLErrorEvent
SQLErrorOperation
SQLEvent
SQLIndexSchema
SQLMode
SQLResult
SQLSchema
SQLSchemaResult
SQLStatement
SQLTableSchema
SQLTransactionLockType
SQLTriggerSchema
SQLUpdateEvent
SQLViewSchema
Desktop:
Clipboard
ClipboardFormats
ClipboardTransferMode
DockIcon
Icon
InteractiveIcon
NativeApplication
NativeProcess
NativeProcessStartupInfo
NotificationType
SystemTrayIcon
Display:
BitmapData
NativeMenu
NativeMenuItem
Screen
Stage
StageDisplayState
StageQuality
Events:
ActivityEvent
AsyncErrorEvent
BrowserInvokeEvent
DataEvent
DatagramSocketDataEvent
DNSResolverEvent
DRMAuthenticateEvent
DRMStatusEvent
ErrorEvent
Event
EventDispatcher
FileListEvent
HTTPStatusEvent
InvokeEvent
InvokeEventReason
IOErrorEvent
LocationChangeEvent
MouseEvent
NativeProcessExitEvent
NetDataEvent
NetMonitorEvent
NetStatusEvent
OutputProgressEvent
ProgressEvent
SampleDataEvent
SecurityErrorEvent
ServerSocketConnectEvent
StatusEvent
StorageVolumeChangeEvent
TimerEvent
UncaughtErrorEvent
UncaughtErrorEvents
File:
File
FileMode
FileStream
StorageVolume
StorageVolumeInfo
Functions:
trace()
generateRandomBytes()
navigateToURL()
sendToURL()
Geom:
Matrix
Point
Rectangle
Media:
AudioDecoder
AudioPlaybackMode
H264Level
H264Profile
H264VideoStreamSettings
ID3Info
InputMediaStream
Microphone
MicrophoneEnhancedMode
MicrophoneEnhancedOptions
Sound
SoundChannel
SoundCodec
SoundLoaderContext
SoundMixer
SoundTransform
VideoCodec
VideoStatus
VideoStreamSettings
Native window:
NativeWindow
NativeWindowBoundsEvent
NativeWindowDisplayState
NativeWindowDisplayStateEvent
NativeWindowInitOptions
NativeWindowRenderMode
NativeWindowResize
NativeWindowSystemChrome
NativeWindowType
Net:
AAAARecord
ARecord
CertificateStatus
DatagramSocket
DNSResolver
FileFilter
InterfaceAddress
IPVersion
LocalConnection
MXRecord
NetConnection
NetMonitor
NetStreamAppendBytesAction
NetStreamMulticastInfo
NetworkInfo
NetworkInterface
ObjectEncoding
PTRRecord
ResourceRecord
Responder
SecureSocket
ServerSocket
SharedObject
SharedObjectFlushStatus
Socket
SRVRecord
URLLoader
URLLoaderDataFormat
URLRequest
URLRequestDefaults
URLRequestHeader
URLRequestMethod
URLStream
URLVariables
XMLSocket
Security:
ReferencesValidationSetting
RevocationCheckSettings
SignatureStatus
SignerTrustSettings
X500DistinguishedName
X509Certificate
XMLSignatureValidator
System:
Capabilities
Security
System
Updater
Ui:
Keyboard
KeyboardType
KeyLocation
Mouse
MouseCursorData
Utils:
Vector
ByteArray
Collator
CollatorMode
CompressionAlgorithm
CurrencyFormatter
CurrencyParseResult
DateTimeFormatter
DateTimeNameContext
DateTimeNameStyle
DateTimeStyle
Endian
HTMLLoader
HTMLPDFCapability
LastOperationStatus
LocaleID
NationalDigitsType
NumberFormatter
NumberParseResult
StringTools
Timer
window.runtime propertywindow.runtime.flash.net.XMLSocket
InheritanceXMLSocket Inheritance EventDispatcher Inheritance Object

Runtime Versions: AIR 1.0,

The XMLSocket class implements client sockets that let the AIR application 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:
  • XML messages are sent over a full-duplex TCP/IP stream socket connection.
  • Each XML message is a complete XML document, terminated by a zero (0) byte.
  • An unlimited number of XML messages can be sent and received over a single XMLSocket connection.

Setting up a server to communicate with the XMLSocket object can be challenging. If your application does not require real-time interactivity, use the URLLoader class instead of the XMLSocket class.

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

SWF files in the local-with-filesystem sandbox may not use sockets.

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:

  • In Flash Player 9.0.124.0 and later, a socket policy file is required for any XMLSocket connection. That is, a socket policy file on the target host is required no matter what port you are connecting to, and is required even if you are connecting to a port on the same host that is serving the SWF file.
  • In Flash Player versions 9.0.115.0 and earlier, if you want to connect to a port number below 1024, or if you want to connect to a host other than the one serving the SWF file, a socket policy file on the target host is required.
  • In Flash Player 9.0.115.0, even if a socket policy file isn't required, a warning is displayed when using the Flash Debug Player if the target host doesn't serve a socket policy file.

However, in Adobe AIR, content in the application security sandbox (content installed with the AIR application) are not restricted by these security limitations.

For more information related to security, see the Flash Player Developer Center Topic: Security.

View the examples

See also



Properties
 PropertyDefined By
  connected : Boolean
[read-only] Indicates whether this XMLSocket object is currently connected.
XMLSocket
 Inheritedconstructor : Object
A reference to the class object or constructor function for a given object instance.
Object
 Inheritedprototype : Object
[static] A reference to the prototype object of a class or function object.
Object
  timeout : int
Indicates the number of milliseconds to wait for a connection.
XMLSocket
Public Methods
 MethodDefined By
  
XMLSocket(host:String = null, port:int = 0)
Creates a new XMLSocket object.
XMLSocket
 Inherited
addEventListener(type:String, listener:Function, useCapture:Boolean = false, priority:int = 0, useWeakReference:Boolean = false):void
Registers an event listener object with an EventDispatcher object so that the listener receives notification of an event.
EventDispatcher
  
close():void
Closes the connection specified by the XMLSocket object.
XMLSocket
  
connect(host:String, port:int):void
Establishes a connection to the specified Internet host using the specified TCP port.
XMLSocket
 Inherited
dispatchEvent(event:Event):Boolean
Dispatches an event into the event flow.
EventDispatcher
 Inherited
hasEventListener(type:String):Boolean
Checks whether the EventDispatcher object has any listeners registered for a specific type of event.
EventDispatcher
 Inherited
hasOwnProperty(name:String):Boolean
Indicates whether an object has a specified property defined.
Object
 Inherited
isPrototypeOf(theClass:Object):Boolean
Indicates whether an instance of the Object class is in the prototype chain of the object specified as the parameter.
Object
 Inherited
propertyIsEnumerable(name:String):Boolean
Indicates whether the specified property exists and is enumerable.
Object
 Inherited
removeEventListener(type:String, listener:Function, useCapture:Boolean = false):void
Removes a listener from the EventDispatcher object.
EventDispatcher
  
send(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.
XMLSocket
 Inherited
setPropertyIsEnumerable(name:String, isEnum:Boolean = true):void
Sets the availability of a dynamic property for loop operations.
Object
 Inherited
toLocaleString():String
Returns the string representation of this object, formatted according to locale-specific conventions.
Object
 Inherited
toString():String
Returns the string representation of the specified object.
Object
 Inherited
valueOf():Object
Returns the primitive value of the specified object.
Object
 Inherited
willTrigger(type:String):Boolean
Checks whether an event listener is registered with this EventDispatcher object or any of its ancestors for the specified event type.
EventDispatcher
Events
 Event Summary Defined By
 Inherited[broadcast event] Dispatched when the Flash Player or AIR application gains operating system focus and becomes active.EventDispatcher
  Dispatched when the server closes the socket connection.XMLSocket
  Dispatched after a successful call to the XMLSocket.connect() method.XMLSocket
  Dispatched after raw data is sent or received.XMLSocket
 Inherited[broadcast event] Dispatched when the Flash Player or AIR application operating loses system focus and is becoming inactive.EventDispatcher
  Dispatched when an input/output error occurs that causes a send or receive operation to fail.XMLSocket
  Dispatched if a call to the XMLSocket.connect() method attempts to connect either to a server outside the caller's security sandbox or to a port lower than 1024.XMLSocket
Property Detail

connected

property
connected:Boolean  [read-only]

Runtime Versions: AIR 1.0,

Indicates whether this XMLSocket object is currently connected. You can also check whether the connection succeeded by registering for the connect event and ioError event.

See also

timeout

property 
timeout:int

Runtime Versions:  1.5

Indicates 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(host:String = null, port:int = 0)

Runtime Versions: AIR 1.0,

Creates a new XMLSocket object. If no parameters are specified, an initially disconnected socket is created. If parameters are specified, a connection is attempted to the specified host and port.

Note: It is strongly advised to use the constructor form without parameters, then add any event listeners, then call the connect method with host and port parameters. This sequence guarantees that all event listeners will work properly.

Parameters
host:String (default = null) — A fully qualified DNS domain name or an IP address in the form .222.333.444. In Flash Player 9.0.115.0 and AIR 1.0 and later, you can specify IPv6 addresses, such as rtmp://[2001:db8:ccc3:ffff:0:444d:555e:666f]. 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.
 
port:int (default = 0) — The TCP port number on the target host used to establish a connection. In Flash Player 9.0.124.0 and later, the target host must serve a socket policy file specifying that socket connections are permitted from the host serving the SWF file to the specified port. In earlier versions of Flash Player, a socket policy file is required only if you want to connect to a port number below 1024, or if you want to connect to a host other than the one serving the SWF file.

See also

Method Detail

close

()method
public function close():void

Runtime Versions: AIR 1.0,

Closes the connection specified by the XMLSocket object. The close event is dispatched only when the server closes the connection; it is not dispatched when you call the close() method.

See also

connect

()method 
public function connect(host:String, port:int):void

Runtime Versions: AIR 1.0,

Establishes a connection to the specified Internet host using the specified TCP port.

If you specify null for the host parameter, the host contacted is the one where the file calling XMLSocket.connect() resides. For example, if the calling file was downloaded from www.adobe.com, specifying null for the host parameter means you are connecting to www.adobe.com.

For more information, see the Flash Player Developer Center Topic: Security.

Parameters

host:String — A fully qualified DNS domain name or an IP address in the form 111.222.333.444. You can also specify null to connect to the host server on which the SWF file resides. If the calling file is a SWF file running in a web browser, host must be in the same domain as the file.
 
port:int — The TCP port number on the target host used to establish a connection. In Flash Player 9.0.124.0 and later, the target host must serve a socket policy file specifying that socket connections are permitted from the host serving the SWF file to the specified port. In earlier versions of Flash Player, a socket policy file is required only if you want to connect to a port number below 1024, or if you want to connect to a host other than the one serving the SWF file.


Events
securityError:SecurityErrorEvent — A connect operation attempted to connect to a host outside the caller's security sandbox, or to a port that requires a socket policy file. Work around either problem by using a socket policy file on the target host.
 
data:DataEvent — Dispatched when raw data has been received.
 
connect:Event — Dispatched when network connection has been established.

Throws
SecurityError — Local untrusted files may not communicate with the Internet. Work around this limitation by reclassifying the file as local-with-networking or trusted.
 
SecurityError — You may not specify a socket port higher than 65535.

See also

send

()method 
public function send(object:*):void

Runtime Versions: AIR 1.0,

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 you do not connect the XMLSocket object to the server using XMLSocket.connect()), the XMLSocket.send() operation fails.

Parameters

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


Throws
IOError — The XMLSocket object is not connected to the server.

See also

Event Detail

close

Event
Event Object Type: flash.events.Event
property Event.type = flash.events.Event.CLOSE

Runtime Versions: AIR 1.0,

Dispatched when the server closes the socket connection. The close event is dispatched only when the server closes the connection; it is not dispatched when you call the XMLSocket.close() method.

The Event.CLOSE constant defines the value of the type property of a close event object.

This event has the following properties:

PropertyValue
bubblesfalse
cancelablefalse; there is no default behavior to cancel.
currentTargetThe object that is actively processing the Event object with an event listener.
targetThe object whose connection has been closed.

connect

Event  
Event Object Type: flash.events.Event
property Event.type = flash.events.Event.CONNECT

Runtime Versions: AIR 1.0,

Dispatched after a successful call to the XMLSocket.connect() method.

The Event.CONNECT constant defines the value of the type property of a connect event object.

This event has the following properties:

PropertyValue
bubblesfalse
cancelablefalse; there is no default behavior to cancel.
currentTargetThe object that is actively processing the Event object with an event listener.
targetThe Socket or XMLSocket object that has established a network connection.

data

Event  
Event Object Type: flash.events.DataEvent
property DataEvent.type = flash.events.DataEvent.DATA

Runtime Versions: AIR 1.0,

Dispatched after raw data is sent or received.

Defines the value of the type property of a data event object.

This event has the following properties:

PropertyValue
bubblesfalse
cancelablefalse; there is no default behavior to cancel.
currentTargetThe object that is actively processing the Event object with an event listener.
dataThe raw data loaded into Flash Player or Adobe AIR.
targetThe XMLSocket object receiving data.

ioError

Event  
Event Object Type: flash.events.IOErrorEvent
property IOErrorEvent.type = flash.events.IOErrorEvent.IO_ERROR

Runtime Versions: AIR 1.0,

Dispatched when an input/output error occurs that causes a send or receive operation to fail.

Defines the value of the type property of an ioError event object.

This event has the following properties:

PropertyValue
bubblesfalse
cancelablefalse; there is no default behavior to cancel.
currentTargetThe object that is actively processing the Event object with an event listener.
errorIDA reference number associated with the specific error (AIR only).
targetThe network object experiencing the input/output error.
textText to be displayed as an error message.

securityError

Event  
Event Object Type: flash.events.SecurityErrorEvent
property SecurityErrorEvent.type = flash.events.SecurityErrorEvent.SECURITY_ERROR

Runtime Versions: AIR 1.0,

Dispatched if a call to the XMLSocket.connect() method attempts to connect either to a server outside the caller's security sandbox or to a port lower than 1024.

The SecurityErrorEvent.SECURITY_ERROR constant defines the value of the type property of a securityError event object.

This event has the following properties:

PropertyValue
bubblesfalse
cancelablefalse; there is no default behavior to cancel.
currentTargetThe object that is actively processing the Event object with an event listener.
targetThe network object reporting the security error.
textText to be displayed as an error message.

See also

Examples

The following example demonstrates sending data using an XMLSocket and printing information during XMLSocket events. This is accomplished using the following steps:
  1. The init() creates a XMLSocket instance named socket and passes socket to configureListeners() (described below) and then calls the XMLSocket object's connect() method using your domain as the host name and port number 8080.
  2. The configureListeners() method adds listeners for each of the supported XMLSocket events:
    • closeHandler(): listens for the close event, which is dispatched after the network connection has been closed.
    • connectHandler(): listens for the connect event, dispatched when the network connection has been established.
    • dataHandler(): listens for the data events, dispatched every time the XMLSocket receives new data.
    • progressHandler(): listens for the progress events, dispatched when a call to send() has been made and while the send is ongoing.
    • securityErrorHandler(): listens for securityError events, which would be dispatched if an attempt was made to access the XMLSocket with the wrong local playback security setting or using a port lower than 1024.
    • ioErrorHandler(): listens for ioError events, which would happen only if an operation to send or receive data failed.

Notes:

  • You need a server running on your domain using port 8080 for this example to work.
  • If you are running Flash Player 9.0.124.0 or later, you need to place a socket policy file on your server that permits socket connections from your domain to port 8080. For information on serving socket policy files, see the Flash Player Developer Center Topic: Setting up a socket policy file server.
<html>
    <head>
      <script src="AIRAliases.js" />
      <script>
        var hostName = "[yourDomain]"; // String
        var port = 8080; // Number
        var socket; // XMLSocket

        function init() {
            socket = new air.XMLSocket();
            configureListeners(socket);
            if (hostName && port) {
                socket.connect(hostName, port);
            }
        }

        function send(data) {
            socket.send(data);
        }

        function configureListeners(dispatcher) {
            dispatcher.addEventListener(air.Event.CLOSE, closeHandler);
            dispatcher.addEventListener(air.Event.CONNECT, connectHandler);
            dispatcher.addEventListener(air.DataEvent.DATA, dataHandler);
            dispatcher.addEventListener(air.IOErrorEvent.IO_ERROR, ioErrorHandler);
            dispatcher.addEventListener(air.ProgressEvent.PROGRESS, progressHandler);
            dispatcher.addEventListener(air.SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
        }

        function closeHandler(event) {
            air.trace("closeHandler: " + event);
        }

        function connectHandler(event) {
            air.trace("connectHandler: " + event);
        }

        function dataHandler(event) {
            air.trace("dataHandler: " + event);
        }

        function ioErrorHandler(event) {
            air.trace("ioErrorHandler: " + event);
        }

        function progressHandler(event) {
            air.trace("progressHandler loaded:" + event.bytesLoaded + " total: " + event.bytesTotal);
        }

        function securityErrorHandler(event) {
            air.trace("securityErrorHandler: " + event);
        }
      </script>
    </head>
    <body onload="init()">
    </body>
</html>