Packageflash.net
Classpublic class SecureSocket
InheritanceSecureSocket Inheritance Socket Inheritance EventDispatcher Inheritance Object

Language version: ActionScript 3.0
Runtime version: AIR 2

The SecureSocket class enables code to make socket connections using the Secure Sockets Layer (SSL) and Transport Layer Security (TLS) protocols.

AIR profile support: This feature is supported on all desktop operating systems, but is not supported on all AIR for TV devices. On mobile devices, it is supported on Android and also supported on iOS starting from AIR 20. You can test for support at run time using the SecureSocket.isSupported property. See AIR Profile Support for more information regarding API support across multiple profiles.

The SSL/TLS protocols provide a mechanism to handle both aspects of a secure socket connection:

  1. Encryption of data communication over the socket
  2. Authentication of the host's identity via its certificate

The supported encryption protocols are SSL 3.1 and higher, and TLS 1.0 and higher. (TLS is the successor protocol for SSL. TLS 1.0 equals SSL 3.1, TLS 1.1 equals SSL 3.2, and so on.) SSL versions 3.0 or lower are not supported.

Validation of the server certificate is performed using the trust store and certificate validation support of the client platform. In addition you can add your own certificates programmatically with the addBinaryChainBuildingCertificate() method.This API isn't supported on iOS currently. Using this API on iOS would throw an exception - "ArgumentError: Error #2004"

The SecureSocket class only connects to servers with valid, trusted certificates. You cannot choose to connect to a server in spite of a problem with its certificate. For example, there is no way to connect to a server with an expired certificate. The same is true for a certificate that doesn't chain to a trusted anchor certificate. The connection will not be made, even though the certificate would be valid otherwise.

The SecureSocket class is useful for performing encrypted communication to a trusted server. In other respects, a SecureSocket object behaves like a regular Socket object.

To use the SecureSocket class, create a SecureSocket object (new SecureSocket()). Next, set up your listeners, and then run SecureSocket.connect(host, port). When you successfully connect to the server, the socket dispatches a connect event. A successful connection is one in which the server's security protocols are supported and its certificate is valid and trusted. If the certificate cannot be validated, the Socket dispatches an IOError event.

Important: The Online Certificate Status Protocol (OCSP) is not supported by all operating systems. Users can also disable OCSP checking on individual computers. If OCSP is not supported or is disabled and a certificate does not contain the information necessary to check revocation using a Certificate Revocation List (CRL), then certificate revocation is not checked. The certificate is accepted if otherwise valid. This scenario could allow a server to use a revoked certificate.

View the examples.

See also

Socket class


Public Properties
 PropertyDefined by
 InheritedbytesAvailable : uint
The number of bytes of data available for reading in the input buffer.
Socket
 InheritedbytesPending : uint
Indicates the number of bytes remaining in the write buffer.
Socket
 Inheritedconnected : Boolean
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
 Inheritedendian : String
Indicates the byte order for the data.
Socket
  isSupported : Boolean
[static][read-only] Indicates whether secure sockets are supported on the current system.
SecureSocket
 InheritedlocalAddress : String
The IP address this socket is bound to on the local machine.
Socket
 InheritedlocalPort : int
The port this socket is bound to on the local machine.
Socket
 InheritedobjectEncoding : 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
 InheritedremoteAddress : String
The IP address of the remote machine to which this socket is connected.
Socket
 InheritedremotePort : int
The port on the remote machine to which this socket is connected.
Socket
  serverCertificate : X509Certificate
[read-only] Holds the X.509 certificate obtained from the server after a secure SSL/TLS connection is established.
SecureSocket
  serverCertificateStatus : String
[read-only] Returns the status of the server's certificate.
SecureSocket
 InheritedtcpNoDelay : Boolean
Whether to use the 'TCP_NODELAY' setting to avoid the use of Nagle's algorithm.
Socket
 Inheritedtimeout : uint
Indicates the number of milliseconds to wait for a connection.
Socket
Public Methods
 MethodDefined by
  
Creates a new SecureSocket object.
SecureSocket
  
Adds an X.509 certificate to the local certificate chain that your system uses for validating the server certificate.
SecureSocket
 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
 Inherited
Closes the socket.
Socket
  
connect(host:String, port:int):void
Connects the socket to the specified host and port using SSL or TLS.
SecureSocket
 Inherited
Dispatches an event into the event flow.
EventDispatcher
 Inherited
Flushes any accumulated data in the socket's output buffer.
Socket
 Inherited
Checks whether the EventDispatcher object has any listeners registered for a specific type of event.
EventDispatcher
 Inherited
Indicates whether an object has a specified property defined.
Object
 Inherited
Indicates whether an instance of the Object class is in the prototype chain of the object specified as the parameter.
Object
 Inherited
Indicates whether the specified property exists and is enumerable.
Object
 Inherited
Reads a Boolean value from the socket.
Socket
 Inherited
Reads a signed byte from the socket.
Socket
 Inherited
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
 Inherited
Reads an IEEE 754 double-precision floating-point number from the socket.
Socket
 Inherited
Reads an IEEE 754 single-precision floating-point number from the socket.
Socket
 Inherited
Reads a signed 32-bit integer from the socket.
Socket
 Inherited
readMultiByte(length:uint, charSet:String):String
Reads a multibyte string from the byte stream, using the specified character set.
Socket
 Inherited
Reads an object from the socket, encoded in AMF serialized format.
Socket
 Inherited
Reads a signed 16-bit integer from the socket.
Socket
 Inherited
Reads an unsigned byte from the socket.
Socket
 Inherited
Reads an unsigned 32-bit integer from the socket.
Socket
 Inherited
Reads an unsigned 16-bit integer from the socket.
Socket
 Inherited
Reads a UTF-8 string from the socket.
Socket
 Inherited
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
Sets the availability of a dynamic property for loop operations.
Object
 Inherited
Returns the string representation of this object, formatted according to locale-specific conventions.
Object
 Inherited
Returns the string representation of the specified object.
Object
 Inherited
Returns the primitive value of the specified object.
Object
 Inherited
Checks whether an event listener is registered with this EventDispatcher object or any of its ancestors for the specified event type.
EventDispatcher
 Inherited
Writes a Boolean value to the socket.
Socket
 Inherited
writeByte(value:int):void
Writes a byte to the socket.
Socket
 Inherited
writeBytes(bytes:ByteArray, offset:uint = 0, length:uint = 0):void
Writes a sequence of bytes from the specified byte array.
Socket
 Inherited
Writes an IEEE 754 double-precision floating-point number to the socket.
Socket
 Inherited
Writes an IEEE 754 single-precision floating-point number to the socket.
Socket
 Inherited
writeInt(value:int):void
Writes a 32-bit signed integer to the socket.
Socket
 Inherited
writeMultiByte(value:String, charSet:String):void
Writes a multibyte string from the byte stream, using the specified character set.
Socket
 Inherited
writeObject(object:*):void
Write an object to the socket in AMF serialized format.
Socket
 Inherited
Writes a 16-bit integer to the socket.
Socket
 Inherited
Writes a 32-bit unsigned integer to the socket.
Socket
 Inherited
Writes the following data to the socket: a 16-bit unsigned integer, which indicates the length of the specified UTF-8 string in bytes, followed by the string itself.
Socket
 Inherited
Writes a UTF-8 string to the socket.
Socket
Events
 EventSummaryDefined 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.SecureSocket
 Inherited Dispatched when the server closes the socket connection.Socket
   Dispatched when a network connection has been established.SecureSocket
 Inherited Dispatched when a network connection has been 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 input or output error occurs that causes a send or receive operation to fail.SecureSocket
 Inherited Dispatched when an input/output error occurs that causes a send or load operation to fail.Socket
 Inherited Dispatched when a socket moves data from its write buffer to the networking transport layer Socket
   Dispatched when a call to SecureSocket.connect() fails because of a security restriction.SecureSocket
 Inherited Dispatched if a call to Socket.connect() attempts to connect to a server prohibited by the caller's security sandbox or to a port lower than 1024 and no socket policy file exists to permit such a connection.Socket
   Dispatched when a socket has received data.SecureSocket
 Inherited Dispatched when a socket has received data.Socket
Property detail
isSupportedproperty
isSupported:Boolean  [read-only]

Language version: ActionScript 3.0
Runtime version: AIR 2

Indicates whether secure sockets are supported on the current system.

Secure sockets are not supported on all platforms. Check this property before attempting to create a SecureSocket instance.

Implementation
    public static function get isSupported():Boolean
serverCertificateproperty 
serverCertificate:X509Certificate  [read-only]

Language version: ActionScript 3.0
Runtime version: AIR 3

Holds the X.509 certificate obtained from the server after a secure SSL/TLS connection is established. If a secure connection is not established, this property is set to null. Currently it is not supported on iOS, and hence it is set to null in case of iOS.

For more information on X.509 certificates, see RFC2459.

Implementation
    public function get serverCertificate():X509Certificate
serverCertificateStatusproperty 
serverCertificateStatus:String  [read-only]

Language version: ActionScript 3.0
Runtime version: AIR 2

Returns the status of the server's certificate.

The status is CertificateStatus.UNKNOWN until the socket attempts to connect to a server. After validation, the status is one of the strings enumerated by the CertificateStatus class. The connection only succeeds when the certificate is valid and trusted. Thus, after a connect event, the value of serverCertificateStatus is always trusted.

Note: Once the certificate has been validated or rejected, the status value is not updated until the next call to the connect() method. Calling close() does not reset the status value to "unknown".

Implementation
    public function get serverCertificateStatus():String

See also

Constructor detail
SecureSocket()constructor
public function SecureSocket()

Language version: ActionScript 3.0
Runtime version: AIR 2

Creates a new SecureSocket object.

Check SecureSocket.isSupported before attempting to create a SecureSocket instance. If SSL 3.0 or TLS 1.0 sockets are not supported, the runtime will throw an IllegalOperationError.


Throws
Error — When SSL Version 3.0 (and higher) or TLS Version 1.0 (and higher) is not supported.
 
SecurityError — Local untrusted SWF files cannot communicate with the Internet. You can work around this problem by reclassifying this SWF file as local-with-networking or trusted.
Method detail
addBinaryChainBuildingCertificate()method
public function addBinaryChainBuildingCertificate(certificate:ByteArray, trusted:Boolean):void

Language version: ActionScript 3.0
Runtime version: AIR 3

Adds an X.509 certificate to the local certificate chain that your system uses for validating the server certificate. The certificate is temporary, and lasts for the duration of the session.

Server certificate validation relies on your system's trust store for certificate chain building and validation. Use this method to programmatically add additional certification chains and trusted anchors.

On Mac OS, the System keychain is the default keychain used during the SSL/TLS handshake process. Any intermediate certificates in that keychain are included when building the certification chain.

The certificate you add with this API must be a DER-encoded X.509 certificate. If the trusted parameter is true, the certificate you add with this API is considered a trusted anchor.

For more information on X.509 certificates, see RFC2459.

Parameters
certificate:ByteArray — A ByteArray object containing a DER-encoded X.509 digital certificate.
 
trusted:Boolean — Set to true to designate this certificate as a trust anchor.

Throws
ArgumentError — When the certificate cannot be added.
connect()method 
public override function connect(host:String, port:int):void

Language version: ActionScript 3.0
Runtime version: AIR 2

Connects the socket to the specified host and port using SSL or TLS.

When you call the SecureSocket.connect() method, the socket attempts SSL/TLS handshaking with the server. If the handshake succeeds, the socket attempts to validate the server certificate. If the certificate is valid and trusted, then the secure socket connection is established, and the socket dispatches a connect event. If the handshake fails or the certificate cannot be validated, the socket dispatches an IOError event. You can check the certificate validation result by reading the serverCertificateStatus property after the IOError event is dispatched. (When a connect event is dispatched, the certificate status is always trusted.)

If the socket was already connected, the existing connection is closed first.

Parameters
host:String — The name or IP address of the host to connect to.
 
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. This includes SSL/TLS handshake errors and failure to successfully validate the host's server certificate.
 
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
Error — When you don't specify a host and the connection fails.
 
SecurityError — When you specify a socket port less than zero or higher than 65535.
Event detail
closeevent 
Event object type: flash.events.Event
Event.type property = flash.events.Event.CLOSE

Language version: ActionScript 3.0
Runtime version: AIR 2

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.
connectevent  
Event object type: flash.events.Event
Event.type property = flash.events.Event.CONNECT

Language version: ActionScript 3.0
Runtime version: AIR 2

Dispatched when a network connection has been 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.
ioErrorevent  
Event object type: flash.events.IOErrorEvent
IOErrorEvent.type property = flash.events.IOErrorEvent.IO_ERROR

Language version: ActionScript 3.0
Runtime version: AIR 2

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

When a server certificate cannot be validated, the error event dispatched is an IOError. In this case, you can check the serverCertificateStatus property to determine the cause of the problem.

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.
securityErrorevent  
Event object type: flash.events.SecurityErrorEvent
SecurityErrorEvent.type property = flash.events.SecurityErrorEvent.SECURITY_ERROR

Language version: ActionScript 3.0
Runtime version: AIR 2

Dispatched when a call to SecureSocket.connect() fails because of a security restriction.

A security error event is dispatched when code running in Flash Player or in AIR outside the application security sandbox attempts to connect to a server in a different domain or to a port lower than 1024 and the server does not provide a policy file that allows the connection. Note that code running within the AIR application sandbox can connect to a server at any domain and on ports below 1024 without a policy file.

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

socketDataevent  
Event object type: flash.events.ProgressEvent
ProgressEvent.type property = flash.events.ProgressEvent.SOCKET_DATA

Language version: ActionScript 3.0
Runtime version: AIR 2

Dispatched when a socket has received data. 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
examples\SecureSocketExample
The following example illustrates how to create and connect a SecureSocket object.
package
{
    import flash.display.Sprite;
	import flash.errors.IOError;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.net.SecureSocket;
	
	public class SecureSocketExample extends Sprite
	{
		private var secureSocket:SecureSocket = new SecureSocket();
		
		public function SecureSocketExample()
		{
			secureSocket.addEventListener( Event.CONNECT, onConnect )
			secureSocket.addEventListener( IOErrorEvent.IO_ERROR, onError );
			
			try
			{
				secureSocket.connect( "208.77.188.166", 443 );
			}
			catch ( error:Error )
			{
				trace ( error.toString() );
			}
		}
		
		private function onConnect( event:Event ):void
		{
			trace("Connected.");
		}
		
		private function onError( error:IOErrorEvent ):void
		{
			trace( error.text + ", " + secureSocket.serverCertificateStatus );
		}
	}
}