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

Language Reference only       
Socket 
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.Socket
InheritanceSocket Inheritance EventDispatcher Inheritance Object

Runtime Versions: AIR 1.0,

The Socket class enables code to establish Transport Control Protocol (TCP) socket connections for sending and receiving binary data asynchronously.

This class is useful for communicating with servers that use binary protocols. For example, you can use this class to connect to mail and news servers.

Working With Sockets

To use the Socket class, begin by creating a Socket object (new Socket()). The best practice is to create the socket object with no parameters, then set up your listeners, and finally call connect() with the host and port parameters of your socket server.

Events drive socket operations. For example, when data is ready for reading from a socket, the socket fires a ProgressEvent.SOCKET_DATA event. You create your own event handlers to process each type of socket event. Sockets send notifications for the following events:

  • Connection established with a socket server
  • Socket closed by a socket server
  • Data is available for reading from the read buffer
  • Data is waiting to be transferred from the write buffer to the network
  • An error occurred

Reading Socket Data: The socket fires a flash.events.ProgressEvent.SOCKET_DATA event when data is ready to be read. Do not sit on a socket in a tight polling loop waiting for data to arrive. Read data only after receiving the ProgressEvent.SOCKET_DATA event. You can read some or all of the available data from the socket.

Writing Socket Data: On some operating systems, flush() is called automatically between execution frames. On other operating systems, such as Windows, the data is never sent unless you call flush() explicitly. It is a good practice to call the flush() method after writing each message (or related group of data) to the socket.

In Adobe AIR, Socket objects are also created when a listening ServerSocket receives a connection from an external process. The Socket representing the connection is dispatched in a ServerSocketConnectEvent. You are responsible for maintaining a reference to this Socket object. If you do not maintain that reference, the Socket object becomes eligible for garbage collection. The runtime destroys objects that are eligible for garbage collection without warning.

Socket Security and Policy Files

SWF content running in the local-with-filesystem security sandbox cannot use sockets.

Socket policy files on the target host specify the hosts from which SWF files can make socket connections. These policy files also specify the ports to which SWF files can connect. 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 Socket 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 socket connection. That is, a socket policy file on the target host is required no matter what port you specify. The policy file is required even if you are connecting to a port on the host serving the SWF file.
  • In Flash Player versions 9.0.115.0 and earlier, a socket policy file is required to connect to a port below 1024. A socket policy file is also required to connect to a host other than the one serving the SWF file.
  • 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.
  • In AIR, a socket policy file is not required for content running in the application security sandbox. Socket policy files are required for any socket connection established by content running outside the AIR application security sandbox.

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

View the examples

See also



Properties
 PropertyDefined By
  bytesAvailable : uint
[read-only] The number of bytes of data available for reading in the input buffer.
Socket
  bytesPending : uint
[read-only] Indicates the amount of data (in bytes) awaiting transfer from the socket's write buffer to the network transport layer.
Socket
  connected : Boolean
[read-only] Indicates whether this Socket object is currently connected.
Socket
 Inheritedconstructor : Object
A reference to the class object or constructor function for a given object instance.
Object
  endian : String
Indicates the byte order for the data.
Socket
  localAddress : String
[read-only] The IP address this socket is bound to on the local machine.
Socket
  localPort : int
[read-only] The port this socket is bound to on the local machine.
Socket
  objectEncoding : uint
Controls the version of AMF used when writing or reading an object.
Socket
 Inheritedprototype : Object
[static] A reference to the prototype object of a class or function object.
Object
  remoteAddress : String
[read-only] The IP address of the remote machine to which this socket is connected.
Socket
  remotePort : int
[read-only] The port on the remote machine to which this socket is connected.
Socket
  timeout : uint
Indicates the number of milliseconds to wait for a connection.
Socket
Public Methods
 MethodDefined By
  
Socket(host:String = null, port:int = 0)
Creates a Socket object.
Socket
 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 socket.
Socket
  
connect(host:String, port:int):void
Connects the socket to the specified host and port.
Socket
 Inherited
dispatchEvent(event:Event):Boolean
Dispatches an event into the event flow.
EventDispatcher
  
flush():void
Flushes any accumulated data in the socket's output buffer.
Socket
 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
  
readBoolean():Boolean
Reads a Boolean value from the socket.
Socket
  
readByte():int
Reads a signed byte from the socket.
Socket
  
readBytes(bytes:ByteArray, offset:uint = 0, length:uint = 0):void
Reads the number of data bytes specified by the length parameter from the socket.
Socket
  
readDouble():Number
Reads an IEEE 754 double-precision floating-point number from the socket.
Socket
  
readFloat():Number
Reads an IEEE 754 single-precision floating-point number from the socket.
Socket
  
readInt():int
Reads a signed 32 bit integer from the socket.
Socket
  
readMultiByte(length:uint, charSet:String):String
Reads a multibyte string from the byte stream, using the specified character set.
Socket
  
Reads an object from the socket, encoded in AMF serialized format.
Socket
  
readShort():int
Reads a signed 16 bit integer from the socket.
Socket
  
Reads an unsigned byte from the socket.
Socket
  
Reads an unsigned 32 bit integer from the socket.
Socket
  
Reads an unsigned 16 bit integer from the socket.
Socket
  
readUTF():String
Reads a UTF-8 string from the socket.
Socket
  
readUTFBytes(length:uint):String
Reads the number of UTF-8 data bytes specified by the length parameter from the socket, and returns a string.
Socket
 Inherited
removeEventListener(type:String, listener:Function, useCapture:Boolean = false):void
Removes a listener from the EventDispatcher object.
EventDispatcher
 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
  
writeBoolean(value:Boolean):void
Writes a Boolean value to the socket.
Socket
  
writeByte(value:int):void
Writes a byte to the socket.
Socket
  
writeBytes(bytes:ByteArray, offset:uint = 0, length:uint = 0):void
Writes a sequence of bytes from the specified byte array.
Socket
  
writeDouble(value:Number):void
Writes an IEEE 754 double-precision floating-point number to the socket.
Socket
  
writeFloat(value:Number):void
Writes an IEEE 754 single-precision floating-point number to the socket.
Socket
  
writeInt(value:int):void
Writes a 32 bit signed integer to the socket.
Socket
  
writeMultiByte(value:String, charSet:String):void
Writes a multibyte string from the byte stream, using the specified character set.
Socket
  
writeObject(object:*):void
Writes an object to the socket in AMF serialized format.
Socket
  
writeShort(value:int):void
Writes a 16 bit integer to the socket.
Socket
  
writeUnsignedInt(value:uint):void
Writes a 32 bit unsigned integer to the socket.
Socket
  
writeUTF(value:String):void
Writes the following data to the socket: A 16 bit unsigned integer.
Socket
  
writeUTFBytes(value:String):void
Writes a UTF-8 string to the socket.
Socket
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.Socket
  Dispatched when a network connection is established.Socket
 Inherited[broadcast event] Dispatched when the Flash Player or AIR application operating loses system focus and is becoming inactive.EventDispatcher
  Dispatched when an IO error causes a send or load operation to fail.Socket
  Dispatched when a socket moves data from its write buffer to the networking transport layer.Socket
  Dispatched if a call to Socket.connect() attempts to connect to a server prohibited by the caller's security sandbox.Socket
  Dispatched when a socket receives data.Socket
Property Detail

bytesAvailable

property
bytesAvailable:uint  [read-only]

Runtime Versions: AIR 1.0,

The number of bytes of data available for reading in the input buffer.

Your code must access bytesAvailable to ensure that sufficient data is available before trying to read it with one of the read methods.

bytesPending

property 
bytesPending:uint  [read-only]

Runtime Versions:  3

Indicates the amount of data (in bytes) awaiting transfer from the socket's write buffer to the network transport layer.

The following operations affect the value of bytesPending:

  • A call to Socket.connect() sets bytesPending to zero.
  • Adding data to the write buffer via a call to one of the Socket.write*() methods updates bytesPending.
  • When the operating system moves data from the write buffer to the network transport layer socket, the system updates bytesPending.
  • A call to Socket.close() sets bytesPending to zero (the write buffer is destroyed when you close the socket).

connected

property 
connected:Boolean  [read-only]

Runtime Versions: AIR 1.0,

Indicates whether this Socket object is currently connected. A call to this property returns a value of true if the socket is currently connected, or false otherwise.

endian

property 
endian:String

Runtime Versions: AIR 1.0,

Indicates the byte order for the data. Possible values are constants from the flash.utils.Endian class, Endian.BIG_ENDIAN or Endian.LITTLE_ENDIAN.

The default value is Endian.BIG_ENDIAN.

See also

localAddress

property 
localAddress:String  [read-only]

Runtime Versions:  2

The IP address this socket is bound to on the local machine.

See also

localPort

property 
localPort:int  [read-only]

Runtime Versions:  2

The port this socket is bound to on the local machine.

See also

objectEncoding

property 
objectEncoding:uint

Runtime Versions: AIR 1.0,

Controls the version of AMF used when writing or reading an object.

See also

remoteAddress

property 
remoteAddress:String  [read-only]

Runtime Versions:  2

The IP address of the remote machine to which this socket is connected.

You can use this property to determine the IP address of a client socket dispatched in a ServerSocketConnectEvent by a ServerSocket object. You can use the DNSResolver class to convert an IP address to a domain name.

See also

remotePort

property 
remotePort:int  [read-only]

Runtime Versions:  2

The port on the remote machine to which this socket is connected.

You can use this property to determine the port number of a client socket dispatched in a ServerSocketConnectEvent by a ServerSocket object.

See also

timeout

property 
timeout:uint

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 (20 seconds).

Constructor Detail

Socket

()Constructor
public function Socket(host:String = null, port:int = 0)

Runtime Versions: AIR 1.0,

Creates a Socket 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. Next, add event listeners, then call the connect method with host and port parameters. This sequence guarantees that all event listeners work properly.

Parameters
host:String (default = null) — A fully qualified DNS domain name or an IP address. IPv4 addresses are specified in dot-decimal notation, such as 192.0.2.0. In Flash Player 9.0.115.0, and AIR 1.0 and later, you can specify IPv6 addresses using hexadecimal-colon notation. This is an example of an IPv6 address: 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 domain from which the SWF file originated.
 
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. The policy file specifies 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 if you want to connect to a port number below 1024, or if you want to connect to a host other than the host serving the SWF file.

Events
connect:Event — Dispatched when a network connection has been established.
 
ioError:IOErrorEvent — Dispatched when an input/output error occurs that causes the connection to fail.
 
securityError:SecurityErrorEventThis error occurs in SWF content. Dispatched if a call to Socket.connect() attempts to connect either to a server that doesn't serve a socket policy file, or to a server whose policy file doesn't grant the calling host access to the specified port. For more information on policy files, see "Website controls (policy files)" in the ActionScript 3.0 Developer's Guide and the Flash Player Developer Center Topic: Security.

Throws
SecurityError — This error occurs in SWF content.
Method Detail

close

()method
public function close():void

Runtime Versions: AIR 1.0,

Closes the socket. You cannot read or write any data after the close() method has been called.

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

You can reuse the Socket object by calling the connect() method on it again.


Throws
IOError — The socket could not be closed, or the socket was not open.

connect

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

Runtime Versions: AIR 1.0,

Connects the socket to the specified host and port.

If the connection fails immediately, either an event is dispatched or an exception is thrown. An error event is dispatched if a host was specified, and an exception is thrown if no host was specified. Otherwise, an event reports the status of the connection. If the socket is already connected, the existing connection is closed first.

Note: For best practices on connecting to a socket, see the Socket class description.

Parameters

host:String — The name or IP address of the host to connect to. If no host is specified, the host that is contacted is the host where the calling file resides. If you do not specify a host, use an event listener to determine whether the connection was successful.
 
port:int — The port number to connect to.


Events
connect:Event — Dispatched when a network connection has been established.
 
ioError:IOErrorEvent — Dispatched if a host is specified and an input/output error occurs that causes the connection to fail.
 
securityError:SecurityErrorEvent — Dispatched if a call to Socket.connect() attempts to connect either to a server that doesn't serve a socket policy file, or to a server whose policy file doesn't grant the calling host access to the specified port. For more information on policy files, see "Website controls (policy files)" in the ActionScript 3.0 Developer's Guide and the Flash Player Developer Center Topic: Security.

Throws
IOError — No host was specified and the connection failed.
 
SecurityError — This error occurs in SWF content.

See also

flush

()method 
public function flush():void

Runtime Versions: AIR 1.0,

Flushes any accumulated data in the socket's output buffer.

On some operating systems, flush() is called automatically between execution frames. On other operating systems, such as Windows, the data is never sent unless you call flush() explicitly. It is a good practice to call the flush() method after each write to the socket.


Throws
IOError — An I/O error occurred on the socket, or the socket is not open.

readBoolean

()method 
public function readBoolean():Boolean

Runtime Versions: AIR 1.0,

Reads a Boolean value from the socket. After reading a single byte, the method returns true if the byte is nonzero, and false otherwise.

Returns
Boolean — A value of true if the byte read is nonzero, otherwise false.

Throws
EOFError — There is insufficient data available to read.
 
IOError — An I/O error occurred on the socket, or the socket is not open.

readByte

()method 
public function readByte():int

Runtime Versions: AIR 1.0,

Reads a signed byte from the socket.

Returns
int — A value from -128 to 127.

Throws
EOFError — There is insufficient data available to read.
 
IOError — An I/O error occurred on the socket, or the socket is not open.

readBytes

()method 
public function readBytes(bytes:ByteArray, offset:uint = 0, length:uint = 0):void

Runtime Versions: AIR 1.0,

Reads the number of data bytes specified by the length parameter from the socket. The bytes are read into the specified byte array, starting at the position indicated by offset.

Parameters

bytes:ByteArray — The ByteArray object to read data into.
 
offset:uint (default = 0) — The offset at which data reading begins in the byte array.
 
length:uint (default = 0) — The number of bytes to read. The default value of 0 causes all available data to be read.


Throws
EOFError — There is insufficient data available to read.
 
IOError — An I/O error occurred on the socket, or the socket is not open.

readDouble

()method 
public function readDouble():Number

Runtime Versions: AIR 1.0,

Reads an IEEE 754 double-precision floating-point number from the socket.

Returns
Number — An IEEE 754 double-precision floating-point number.

Throws
EOFError — There is insufficient data available to read.
 
IOError — An I/O error occurred on the socket, or the socket is not open.

readFloat

()method 
public function readFloat():Number

Runtime Versions: AIR 1.0,

Reads an IEEE 754 single-precision floating-point number from the socket.

Returns
Number — An IEEE 754 single-precision floating-point number.

Throws
EOFError — There is insufficient data available to read.
 
IOError — An I/O error occurred on the socket, or the socket is not open.

readInt

()method 
public function readInt():int

Runtime Versions: AIR 1.0,

Reads a signed 32 bit integer from the socket.

Returns
int — A value from -2147483648 to 2147483647.

Throws
EOFError — There is insufficient data available to read.
 
IOError — An I/O error occurred on the socket, or the socket is not open.

readMultiByte

()method 
public function readMultiByte(length:uint, charSet:String):String

Runtime Versions: AIR 1.0,

Reads a multibyte string from the byte stream, using the specified character set.

Parameters

length:uint — The number of bytes from the byte stream to read.
 
charSet:String — The string denoting the character set to use to interpret the bytes. Possible character set strings include "shift_jis", "CN-GB", and "iso-8859-1". For a complete list, see Supported Character Sets.

Note: If the system does not recognize the charSet parameter, the application uses the system's default code page as the character set. For example, a value for the charSet parameter, as in myTest.readMultiByte(22, "iso-8859-01") that uses 01 instead of 1 might work on your development machine, but not on another machine. On the other machine, the application uses the system's default code page.

Returns
String — A UTF-8 encoded string.

Throws
EOFError — There is insufficient data available to read.

readObject

()method 
public function readObject():*

Runtime Versions: AIR 1.0,

Reads an object from the socket, encoded in AMF serialized format.

Returns
* — The deserialized object

Throws
EOFError — There is insufficient data available to read.
 
IOError — An I/O error occurred on the socket, or the socket is not open.

See also

readShort

()method 
public function readShort():int

Runtime Versions: AIR 1.0,

Reads a signed 16 bit integer from the socket.

Returns
int — A value from -32768 to 32767.

Throws
EOFError — There is insufficient data available to read.
 
IOError — An I/O error occurred on the socket, or the socket is not open.

readUnsignedByte

()method 
public function readUnsignedByte():uint

Runtime Versions: AIR 1.0,

Reads an unsigned byte from the socket.

Returns
uint — A value from 0 to 255.

Throws
EOFError — There is insufficient data available to read.
 
IOError — An I/O error occurred on the socket, or the socket is not open.

readUnsignedInt

()method 
public function readUnsignedInt():uint

Runtime Versions: AIR 1.0,

Reads an unsigned 32 bit integer from the socket.

Returns
uint — A value from 0 to 4294967295.

Throws
EOFError — There is insufficient data available to read.
 
IOError — An I/O error occurred on the socket, or the socket is not open.

readUnsignedShort

()method 
public function readUnsignedShort():uint

Runtime Versions: AIR 1.0,

Reads an unsigned 16 bit integer from the socket.

Returns
uint — A value from 0 to 65535.

Throws
EOFError — There is insufficient data available to read.
 
IOError — An I/O error occurred on the socket, or the socket is not open.

readUTF

()method 
public function readUTF():String

Runtime Versions: AIR 1.0,

Reads a UTF-8 string from the socket. The method expects that the string is prefixed with an unsigned short integer that indicates the length in bytes.

Returns
String — A UTF-8 string.

Throws
EOFError — There is insufficient data available to read.
 
IOError — An I/O error occurred on the socket, or the socket is not open.

readUTFBytes

()method 
public function readUTFBytes(length:uint):String

Runtime Versions: AIR 1.0,

Reads the number of UTF-8 data bytes specified by the length parameter from the socket, and returns a string.

Parameters

length:uint — The number of bytes to read.

Returns
String — A UTF-8 string.

Throws
EOFError — There is insufficient data available to read.
 
IOError — An I/O error occurred on the socket, or the socket is not open.

writeBoolean

()method 
public function writeBoolean(value:Boolean):void

Runtime Versions: AIR 1.0,

Writes a Boolean value to the socket. This method writes a single byte, with either a value of 1 (true) or 0 (false).

Parameters

value:Boolean — The value to write to the socket: 1 (true) or 0 (false).


Throws
IOError — An I/O error occurred on the socket, or the socket is not open.

See also

writeByte

()method 
public function writeByte(value:int):void

Runtime Versions: AIR 1.0,

Writes a byte to the socket.

Parameters

value:int — The value to write to the socket. The low 8 bits of the value are used; the high 24 bits are ignored.


Throws
IOError — An I/O error occurred on the socket, or the socket is not open.

See also

writeBytes

()method 
public function writeBytes(bytes:ByteArray, offset:uint = 0, length:uint = 0):void

Runtime Versions: AIR 1.0,

Writes a sequence of bytes from the specified byte array. The write operation starts at the position specified by offset.

If you omit the length parameter the default length of 0 causes the method to write the entire buffer starting at offset.

If you also omit the offset parameter, the method writes the entire buffer.

Parameters

bytes:ByteArray — The ByteArray object to write data from.
 
offset:uint (default = 0) — The zero-based offset into the bytes ByteArray object at which data writing begins.
 
length:uint (default = 0) — The number of bytes to write. The default value of 0 causes the method to write the entire buffer. Writing starts at the value specified by the offset parameter.


Throws
IOError — An I/O error occurred on the socket, or the socket is not open.
 
RangeError — If offset is greater than the length of the ByteArray specified in bytes, or if the amount of data specified by offset plus length exceeds the data available.

See also

writeDouble

()method 
public function writeDouble(value:Number):void

Runtime Versions: AIR 1.0,

Writes an IEEE 754 double-precision floating-point number to the socket.

Parameters

value:Number — The value to write to the socket.


Throws
IOError — An I/O error occurred on the socket, or the socket is not open.

See also

writeFloat

()method 
public function writeFloat(value:Number):void

Runtime Versions: AIR 1.0,

Writes an IEEE 754 single-precision floating-point number to the socket.

Parameters

value:Number — The value to write to the socket.


Throws
IOError — An I/O error occurred on the socket, or the socket is not open.

See also

writeInt

()method 
public function writeInt(value:int):void

Runtime Versions: AIR 1.0,

Writes a 32 bit signed integer to the socket.

Parameters

value:int — The value to write to the socket.


Throws
IOError — An I/O error occurred on the socket, or the socket is not open.

See also

writeMultiByte

()method 
public function writeMultiByte(value:String, charSet:String):void

Runtime Versions: AIR 1.0,

Writes a multibyte string from the byte stream, using the specified character set.

Parameters

value:String — The string content.
 
charSet:String — The string denoting the character set to use to interpret the bytes. Possible character set strings include "shift_jis", "CN-GB", and "iso-8859-1". For a complete list, see Supported Character Sets.

See also

writeObject

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

Runtime Versions: AIR 1.0,

Writes an object to the socket in AMF serialized format.

Parameters

object:* — The object to be serialized.


Throws
IOError — An I/O error occurred on the socket, or the socket is not open.

See also

writeShort

()method 
public function writeShort(value:int):void

Runtime Versions: AIR 1.0,

Writes a 16 bit integer to the socket. The bytes written are as follows:

(v >> 8) & 0xff v & 0xff

The low 16 bits of the parameter are used; the high 16 bits are ignored.

Parameters

value:int — The value to write to the socket.


Throws
IOError — An I/O error occurred on the socket, or the socket is not open.

See also

writeUnsignedInt

()method 
public function writeUnsignedInt(value:uint):void

Runtime Versions: AIR 1.0,

Writes a 32 bit unsigned integer to the socket.

Parameters

value:uint — The value to write to the socket.


Throws
IOError — An I/O error occurred on the socket, or the socket is not open.

See also

writeUTF

()method 
public function writeUTF(value:String):void

Runtime Versions: AIR 1.0,

Writes the following data to the socket:

  • A 16 bit unsigned integer. The integer indicates the length in bytes of the specified UTF-8 string.
  • The specified UTF-8 string.

Before writing the string, the method calculates the number of bytes necessary to represent all characters of the string.

Parameters

value:String — The string to write to the socket.


Throws
RangeError — The length is larger than 65535.
 
IOError — An I/O error occurred on the socket, or the socket is not open.

See also

writeUTFBytes

()method 
public function writeUTFBytes(value:String):void

Runtime Versions: AIR 1.0,

Writes a UTF-8 string to the socket.

Parameters

value:String — The string to write to the socket.


Throws
IOError — An I/O error occurred on the socket, or the socket is not open.

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 Socket.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 when a network connection is established.

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.

ioError

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

Runtime Versions: AIR 1.0,

Dispatched when an IO error causes a send or load 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.

outputProgress

Event  
Event Object Type: flash.events.OutputProgressEvent
property OutputProgressEvent.type = flash.events.OutputProgressEvent.OUTPUT_PROGRESS

Runtime Versions:  3

Dispatched when a socket moves data from its write buffer to the networking transport layer. Use the bytesPending property on this event object to determine how much data is pending in the write buffer.

You can use this event to prevent data loss when, for example, a user prematurely closes an application employing sockets. Ensure that the socket property bytesPending equals zero before you close a socket or allow the socket to be garbage-collected.

For more information about this event, along with an example, see Socket Improvements in AIR 3.

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

This event has the following properties:

PropertyValue
bubblesfalse
bytesPendingThe number of bytes remaining to be written at the time the listener processes the event.
bytesTotalThe total number of bytes that ultimately will be written if the write process succeeds.
cancelablefalse; there is no default behavior to cancel.
currentTargetThe object that is actively processing the Event object with an event listener.
targetThe FileStream object reporting progress.

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 Socket.connect() attempts to connect to a server prohibited by the caller's security sandbox. This event is also dispatched if the port ID is lower than 1024 and no socket policy file exists to permit such a connection.

Note: In an AIR application, content running in the application security sandbox can connect without a socket policy file to any server and port number.

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

socketData

Event  
Event Object Type: flash.events.ProgressEvent
property ProgressEvent.type = flash.events.ProgressEvent.SOCKET_DATA

Runtime Versions: AIR 1.0,

Dispatched when a socket receives data.

The data received by the socket remains in the socket until it is read. You can read all or some of the received data upon notification of this event.

Note: Events of type socketData do not use the ProgressEvent.bytesTotal property.

Defines the value of the type property of a socketData 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.
bytesLoadedThe number of items or bytes loaded at the time the listener processes the event.
bytesTotal0; this property is not used by socketData event objects.
targetThe socket reporting progress.
Examples

The following example reads from and writes to a socket and outputs information transmitted during socket events.

Note: To test this example, do the following:

  1. Add the AIRAliases.js file to the project directory.
  2. Change the code so that the Socket() constructor points to a valid URL and port.
  3. Create an application descriptor file for the project, and test the project using ADL.
<html>
<head>
    <script src="AIRAliases.js" />
    <script>
    var socket;
    var response;
    function init() {
        socket = new air.Socket("localhost", 80);
        socket.addEventListener(air.Event.CLOSE, closeHandler);
        socket.addEventListener(air.Event.CONNECT, connectHandler);
        socket.addEventListener(air.IOErrorEvent.IO_ERROR, ioErrorHandler);
        socket.addEventListener(air.SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
        socket.addEventListener(air.ProgressEvent.SOCKET_DATA, socketDataHandler);
    }
    function writeln(str) {
        str += "\n";
        try {
            socket.writeUTFBytes(str);
        }
        catch(e) {
            air.trace(e);
        }
    }
    function sendRequest() {
        air.trace("sendRequest");
        response = "";
        writeln("GET /");
        socket.flush();
    }
    function readResponse() {
        var str = socket.readUTFBytes(socket.bytesAvailable);
        response += str;
    }
    function closeHandler(event) {
        air.trace("closeHandler: " + event);
        air.trace(response.toString());
    }
    function connectHandler(event) {
        air.trace("connectHandler: " + event);
        sendRequest();
    }
    function ioErrorHandler(event) {
        air.trace("ioErrorHandler: " + event);
    }
    function securityErrorHandler(event) {
        air.trace("securityErrorHandler: " + event);
    }
    function socketDataHandler(event) {
        air.trace("socketDataHandler: " + event);
        readResponse();
    }
    </script>
</head>
<body onload='init()'>
</body>
</html>