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

You can test for support at run time using the SecureSocket.isSupported property.

OpenFL target support: This feature is supported on all desktop operating systems, on iOS, and on Android. It is not supported on non-sys targets.

Adobe 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. 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 all systems currently. Using this API on some systems will 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.

Events:

close

Dispatched when the server closes the socket connection.

connect

Dispatched when a network connection has been established.

ioError

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

securityError

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

socketData

Dispatched when a socket has received data.

Static variables

staticread onlyisSupported:Bool

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.

Constructor

new()

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:

IllegalOperationError

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.

Variables

read onlyserverCertificate:X509Certificate

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.

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

read onlyserverCertificateStatus:CertificateStatus

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".

Methods

addBinaryChainBuildingCertificate(certificate:ByteArray, trusted:Bool):Void

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

A ByteArray object containing a DER-encoded X.509 digital certificate.

trusted

Set to true to designate this certificate as a trust anchor.

Throws:

ArgumentError

When the certificate cannot be added.

connect(host:String, port:Int):Void

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

The name or IP address of the host to connect to.

port

The port number to connect to.

Throws:

IOError

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.

Inherited Variables

Defined by Socket

read onlybytesAvailable:Int

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.

read onlybytesPending:Int

Indicates the number of bytes remaining in the write buffer.

Use this property in combination with with the OutputProgressEvent. An OutputProgressEvent is thrown whenever data is written from the write buffer to the network. In the event handler, you can check bytesPending to see how much data is still left in the buffer waiting to be written. When bytesPending returns 0, it means that all the data has been transferred from the write buffer to the network, and it is safe to do things like remove event handlers, null out socket references, start the next upload in a queue, etc.

read onlyconnected:Bool

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:Endian

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

read onlylocalAddress:String

Available on AIR, Android, Flash, Linux, Neko, Windows, iOS, macOS

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

read onlylocalPort:Int

Available on AIR, Android, Flash, Linux, Neko, Windows, iOS, macOS

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

objectEncoding:ObjectEncoding

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

read onlyremoteAddress:String

Available on AIR, Android, Flash, Linux, Neko, Windows, iOS, macOS

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.

read onlyremotePort:Int

Available on AIR, Android, Flash, Linux, Neko, Windows, iOS, macOS

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.

timeout:Int

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).

Inherited Methods

Defined by Socket

close():Void

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.

flush():Void

Flushes any accumulated data in the socket's output buffer. On some operating systems, flush() is called automatically between execution frames, but on other operating systems, such as Windows, the data is never sent unless you call flush() explicitly. To ensure your application behaves reliably across all operating systems, it is a good practice to call the flush() method after writing each message (or related group of data) to the socket.

Throws:

IOError

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

readBoolean():Bool

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:

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():Int

Reads a signed byte from the socket.

Returns:

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.

@:value({ length : 0, offset : 0 })readBytes(bytes:ByteArray, offset:Int = 0, length:Int = 0):Void

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

The ByteArray object to read data into.

offset

The offset at which data reading should begin in the byte array.

length

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():Float

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

Returns:

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():Float

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

Returns:

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():Int

Reads a signed 32-bit integer from the socket.

Returns:

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(length:Int, charSet:String):String

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

Parameters:

length

The number of bytes from the byte stream to read.

charSet

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 <a href="../../charset-codes.html">Supported Character Sets. Note: If the value for the charSet parameter is not recognized by the current system, then 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 will use the system's default code page.

Returns:

A UTF-8 encoded string.

Throws:

EOFError

There is insufficient data available to read.

readObject():Dynamic

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.

readShort():Int

Reads a signed 16-bit integer from the socket.

Returns:

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.

readUTF():String

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

Returns:

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(length:Int):String

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

Parameters:

length

The number of bytes to read.

Returns:

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.

readUnsignedByte():Int

Reads an unsigned byte from the socket.

Returns:

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():Int

Reads an unsigned 32-bit integer from the socket.

Returns:

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():Int

Reads an unsigned 16-bit integer from the socket.

Returns:

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.

writeBoolean(value:Bool):Void

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

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.

writeByte(value:Int):Void

Writes a byte to the socket.

Parameters:

value

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.

@:value({ length : 0, offset : 0 })writeBytes(bytes:ByteArray, offset:Int = 0, length:Int = 0):Void

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 entire buffer is written.

Parameters:

bytes

The ByteArray object to write data from.

offset

The zero-based offset into the bytes ByteArray object at which data writing should begin.

length

The number of bytes to write. The default value of 0 causes the entire buffer to be written, starting 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 to be written by offset plus length exceeds the data available.

writeDouble(value:Float):Void

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

Parameters:

value

The value to write to the socket.

Throws:

IOError

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

writeFloat(value:Float):Void

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

Parameters:

value

The value to write to the socket.

Throws:

IOError

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

writeInt(value:Int):Void

Writes a 32-bit signed integer to the socket.

Parameters:

value

The value to write to the socket.

Throws:

IOError

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

writeMultiByte(value:String, charSet:String):Void

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

Parameters:

value

The string value to be written.

charSet

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 <a href="../../charset-codes.html">Supported Character Sets.

writeObject(object:Dynamic):Void

Write 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.

writeShort(value:Int):Void

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

The value to write to the socket.

Throws:

IOError

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

writeUTF(value:String):Void

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. Before writing the string, the method calculates the number of bytes that are needed to represent all characters of the string.

Parameters:

value

The string to write to the socket.

Throws:

IOError

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

RangeError

The length is larger than 65535.

writeUTFBytes(value:String):Void

Writes a UTF-8 string to the socket.

Parameters:

value

The string to write to the socket.

Throws:

IOError

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

writeUnsignedInt(value:Int):Void

Writes a 32-bit unsigned integer to the socket.

Parameters:

value

The value to write to the socket.

Throws:

IOError

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

Defined by EventDispatcher

@:value({ useWeakReference : false, priority : 0, useCapture : false })addEventListener<T>(type:EventType<T>, listener:T ‑> Void, useCapture:Bool = false, priority:Int = 0, useWeakReference:Bool = false):Void

Registers an event listener object with an EventDispatcher object so that the listener receives notification of an event. You can register event listeners on all nodes in the display list for a specific type of event, phase, and priority.

After you successfully register an event listener, you cannot change its priority through additional calls to addEventListener(). To change a listener's priority, you must first call removeListener(). Then you can register the listener again with the new priority level.

Keep in mind that after the listener is registered, subsequent calls to addEventListener() with a different type or useCapture value result in the creation of a separate listener registration. For example, if you first register a listener with useCapture set to true, it listens only during the capture phase. If you call addEventListener() again using the same listener object, but with useCapture set to false, you have two separate listeners: one that listens during the capture phase and another that listens during the target and bubbling phases.

You cannot register an event listener for only the target phase or the bubbling phase. Those phases are coupled during registration because bubbling applies only to the ancestors of the target node.

If you no longer need an event listener, remove it by calling removeEventListener(), or memory problems could result. Event listeners are not automatically removed from memory because the garbage collector does not remove the listener as long as the dispatching object exists(unless the useWeakReference parameter is set to true).

Copying an EventDispatcher instance does not copy the event listeners attached to it.(If your newly created node needs an event listener, you must attach the listener after creating the node.) However, if you move an EventDispatcher instance, the event listeners attached to it move along with it.

If the event listener is being registered on a node while an event is being processed on this node, the event listener is not triggered during the current phase but can be triggered during a later phase in the event flow, such as the bubbling phase.

If an event listener is removed from a node while an event is being processed on the node, it is still triggered by the current actions. After it is removed, the event listener is never invoked again(unless registered again for future processing).

Parameters:

type

The type of event.

useCapture

Determines whether the listener works in the capture phase or the target and bubbling phases. If useCapture is set to true, the listener processes the event only during the capture phase and not in the target or bubbling phase. If useCapture is false, the listener processes the event only during the target or bubbling phase. To listen for the event in all three phases, call addEventListener twice, once with useCapture set to true, then again with useCapture set to false.

priority

The priority level of the event listener. The priority is designated by a signed 32-bit integer. The higher the number, the higher the priority. All listeners with priority n are processed before listeners of priority n-1. If two or more listeners share the same priority, they are processed in the order in which they were added. The default priority is 0.

useWeakReference

Determines whether the reference to the listener is strong or weak. A strong reference(the default) prevents your listener from being garbage-collected. A weak reference does not.

Class-level member functions are not subject to garbage collection, so you can set useWeakReference to true for class-level member functions without subjecting them to garbage collection. If you set useWeakReference to true for a listener that is a nested inner function, the function will be garbage-collected and no longer persistent. If you create references to the inner function(save it in another variable) then it is not garbage-collected and stays persistent.

Weak references are supported on some OpenFL targets only, including html5, cpp, and flash/air. On other targets, this parameter is ignored, and the reference will be strong instead.

Throws:

ArgumentError

The listener specified is not a function.

dispatchEvent(event:Event):Bool

Dispatches an event into the event flow. The event target is the EventDispatcher object upon which the dispatchEvent() method is called.

Parameters:

event

The Event object that is dispatched into the event flow. If the event is being redispatched, a clone of the event is created automatically. After an event is dispatched, its target property cannot be changed, so you must create a new copy of the event for redispatching to work.

Returns:

A value of true if the event was successfully dispatched. A value of false indicates failure or that preventDefault() was called on the event.

Throws:

Error

The event dispatch recursion limit has been reached.

hasEventListener(type:String):Bool

Checks whether the EventDispatcher object has any listeners registered for a specific type of event. This allows you to determine where an EventDispatcher object has altered handling of an event type in the event flow hierarchy. To determine whether a specific event type actually triggers an event listener, use willTrigger().

The difference between hasEventListener() and willTrigger() is that hasEventListener() examines only the object to which it belongs, whereas willTrigger() examines the entire event flow for the event specified by the type parameter.

When hasEventListener() is called from a LoaderInfo object, only the listeners that the caller can access are considered.

Parameters:

type

The type of event.

Returns:

A value of true if a listener of the specified type is registered; false otherwise.

@:value({ useCapture : false })removeEventListener<T>(type:EventType<T>, listener:T ‑> Void, useCapture:Bool = false):Void

Removes a listener from the EventDispatcher object. If there is no matching listener registered with the EventDispatcher object, a call to this method has no effect.

Parameters:

type

The type of event.

useCapture

Specifies whether the listener was registered for the capture phase or the target and bubbling phases. If the listener was registered for both the capture phase and the target and bubbling phases, two calls to removeEventListener() are required to remove both, one call with useCapture() set to true, and another call with useCapture() set to false.

toString():String

willTrigger(type:String):Bool

Checks whether an event listener is registered with this EventDispatcher object or any of its ancestors for the specified event type. This method returns true if an event listener is triggered during any phase of the event flow when an event of the specified type is dispatched to this EventDispatcher object or any of its descendants.

The difference between the hasEventListener() and the willTrigger() methods is that hasEventListener() examines only the object to which it belongs, whereas the willTrigger() method examines the entire event flow for the event specified by the type parameter.

When willTrigger() is called from a LoaderInfo object, only the listeners that the caller can access are considered.

Parameters:

type

The type of event.

Returns:

A value of true if a listener of the specified type will be triggered; false otherwise.