Packageflash.net
Classpublic class ServerSocket
InheritanceServerSocket Inheritance EventDispatcher Inheritance Object

Language version: ActionScript 3.0
Runtime version: AIR 2

The ServerSocket class allows code to act as a server for Transport Control Protocol (TCP) connections.

AIR profile support: This feature is supported on all desktop operating systems, on iOS (starting with AIR 3.8), and on Android (starting with AIR 3.8). This feature is not supported on AIR for TV devices. You can test for support at run time using the ServerSocket.isSupported property. See AIR Profile Support for more information regarding API support across multiple profiles.

A TCP server listens for incoming connections from remote clients. When a client attempts to connect, the ServerSocket dispatches a connect event. The ServerSocketConnectEvent object dispatched for the event provides a Socket object representing the TCP connection between the server and the client. Use this Socket object for subsequent communication with the connected client. You can get the client address and port from the Socket object, if needed.

Note: Your application is responsible for maintaining a reference to the client Socket object. If you don't, the object is eligible for garbage collection and may be destroyed by the runtime without warning.

To put a ServerSocket object into the listening state, call the listen() method. In the listening state, the server socket object dispatches connect events whenever a client using the TCP protocol attempts to connect to the bound address and port. The ServerSocket object continues to listen for additional connections until you call the close() method.

TCP connections are persistent — they exist until one side of the connection closes it (or a serious network failure occurs). Any data sent over the connection is broken into transmittable packets and reassembled on the other end. All packets are guaranteed to arrive (within reason) — any lost packets are retransmitted. In general, the TCP protocol manages the available network bandwidth better than the UDP protocol. Most AIR applications that require socket communications should use the ServerSocket and Socket classes rather than the DatagramSocket class.

The ServerSocket class can only be used in Adobe AIR applications and only in the application security sandbox.

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

View the examples.

See also

ServerSocketConnectEvent class
Socket class
XMLSocket class
DatagramSocket class


Public Properties
 PropertyDefined by
  bound : Boolean
[read-only] Indicates whether the socket is bound to a local address and port.
ServerSocket
 Inheritedconstructor : Object
A reference to the class object or constructor function for a given object instance.
Object
  isSupported : Boolean
[static][read-only] Indicates whether or not ServerSocket features are supported in the run-time environment.
ServerSocket
  listening : Boolean
[read-only] Indicates whether the server socket is listening for incoming connections.
ServerSocket
  localAddress : String
[read-only] The IP address on which the socket is listening.
ServerSocket
  localPort : int
[read-only] The port on which the socket is listening.
ServerSocket
 Inheritedprototype : Object
[static] A reference to the prototype object of a class or function object.
Object
Public Methods
 MethodDefined by
  
Creates a ServerSocket object.
ServerSocket
 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
  
bind(localPort:int = 0, localAddress:String = "0.0.0.0"):void
Binds this socket to the specified local address and port.
ServerSocket
  
Closes the socket and stops listening for connections.
ServerSocket
 Inherited
Dispatches an event into the event flow.
EventDispatcher
 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
  
listen(backlog:int = 0):void
Initiates listening for TCP connections on the bound IP address and port.
ServerSocket
 Inherited
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
 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
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 operating system closes this socket.ServerSocket
   Dispatched when a remote socket seeks to connect to this server socket.ServerSocket
 Inherited [broadcast event] Dispatched when the Flash Player or AIR application operating loses system focus and is becoming inactive.EventDispatcher
Property detail
boundproperty
bound:Boolean  [read-only]

Language version: ActionScript 3.0
Runtime version: AIR 2

Indicates whether the socket is bound to a local address and port.

Implementation
    public function get bound():Boolean

See also

isSupportedproperty 
isSupported:Boolean  [read-only]

Language version: ActionScript 3.0
Runtime version: AIR 2

Indicates whether or not ServerSocket features are supported in the run-time environment.

Implementation
    public static function get isSupported():Boolean
listeningproperty 
listening:Boolean  [read-only]

Language version: ActionScript 3.0
Runtime version: AIR 2

Indicates whether the server socket is listening for incoming connections.

Implementation
    public function get listening():Boolean

See also

localAddressproperty 
localAddress:String  [read-only]

Language version: ActionScript 3.0
Runtime version: AIR 2

The IP address on which the socket is listening.

Implementation
    public function get localAddress():String

See also

localPortproperty 
localPort:int  [read-only]

Language version: ActionScript 3.0
Runtime version: AIR 2

The port on which the socket is listening.

Implementation
    public function get localPort():int

See also

Constructor detail
ServerSocket()constructor
public function ServerSocket()

Language version: ActionScript 3.0
Runtime version: AIR 2

Creates a ServerSocket object.


Throws
SecurityError — This error occurs ff the calling content is running outside the AIR application security sandbox.
Method detail
bind()method
public function bind(localPort:int = 0, localAddress:String = "0.0.0.0"):void

Language version: ActionScript 3.0
Runtime version: AIR 2

Binds this socket to the specified local address and port.

Parameters
localPort:int (default = 0) — The number of the port to bind to on the local computer. If localPort, is set to 0 (the default), the next available system port is bound. Permission to connect to a port number below 1024 is subject to the system security policy. On Mac and Linux systems, for example, the application must be running with root privileges to connect to ports below 1024.
 
localAddress:String (default = "0.0.0.0") — The IP address on the local machine to bind to. This address can be an IPv4 or IPv6 address. If localAddress is set to 0.0.0.0 (the default), the socket listens on all available IPv4 addresses. To listen on all available IPv6 addresses, you must specify "::" as the localAddress argument. To use an IPv6 address, the computer and network must both be configured to support IPv6. Furthermore, a socket bound to an IPv4 address cannot connect to a socket with an IPv6 address. Likewise, a socket bound to an IPv6 address cannot connect to a socket with an IPv4 address. The type of address must match.

Throws
RangeError — This error occurs when localPort is less than 0 or greater than 65535.
 
ArgumentError — This error occurs when localAddress is not a syntactically well-formed IP address.
 
Error — when the socket cannot be bound, such as when:
  • the underlying network socket (IP and port) is already in bound by another object or process.
  • the application is running under a user account that does not have the privileges necessary to bind to the port. Privilege issues typically occur when attempting to bind to well known ports (localPort < 1024)
  • this ServerSocket object is already bound. (Call close() before binding to a different socket.)
  • when localAddress is not a valid local address.
close()method 
public function close():void

Language version: ActionScript 3.0
Runtime version: AIR 2

Closes the socket and stops listening for connections.

Closed sockets cannot be reopened. Create a new ServerSocket instance instead.


Throws
Error — This error occurs if the socket could not be closed, or the socket was not open.
listen()method 
public function listen(backlog:int = 0):void

Language version: ActionScript 3.0
Runtime version: AIR 2

Initiates listening for TCP connections on the bound IP address and port.

The listen() method returns immediately. Once you call listen(), the ServerSocket object dispatches a connect event whenever a connection attempt is made. The socket property of the ServerSocketConnectEvent event object references a Socket object representing the server-client connection.

The backlog parameter specifies how many pending connections are queued while the connect events are processed by your application. If the queue is full, additional connections are denied without a connect event being dispatched. If the default value of zero is specified, then the system-maximum queue length is used. This length varies by platform and can be configured per computer. If the specified value exceeds the system-maximum length, then the system-maximum length is used instead. No means for discovering the actual backlog value is provided. (The system-maximum value is determined by the SOMAXCONN setting of the TCP network subsystem on the host computer.)

Parameters
backlog:int (default = 0) — The maximum length of the queue of pending connections. If backlog is 0, the queue length is set to the maximum system value.

Throws
Error — This error occurs if the socket is not open or bound. This error also occurs if the call to listen() fails for any other reason.
 
RangeError — This error occurs if the backlog parameter is less than zero.
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 operating system closes this socket.

The close event is not dispatched when the ServerSocket close() method is called. If other objects in your application rely on the close event, you can dispatch the event manually before calling the 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.ServerSocketConnectEvent

Language version: ActionScript 3.0
Runtime version: AIR 2

Dispatched when a remote socket seeks to connect to this server socket.

Examples
examples\ServerSocketExample
The following example creates a socket server. To use the server, bind the socket to a local port and then connect to that port from another application. The server only understands UTF-8 strings.
package
{
    import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.events.ProgressEvent;
	import flash.events.ServerSocketConnectEvent;
	import flash.net.ServerSocket;
	import flash.net.Socket;
	import flash.text.TextField;
	import flash.text.TextFieldType;
	import flash.utils.ByteArray;
		
	public class ServerSocketExample extends Sprite
	{
		private var serverSocket:ServerSocket = new ServerSocket();
		private var clientSocket:Socket;

		private var localIP:TextField;
		private var localPort:TextField;
		private var logField:TextField;
		private var message:TextField;

		public function ServerSocketExample()
		{
			setupUI();
		}
		
		private function onConnect( event:ServerSocketConnectEvent ):void
		{
			clientSocket = event.socket;
			clientSocket.addEventListener( ProgressEvent.SOCKET_DATA, onClientSocketData );
			log( "Connection from " + clientSocket.remoteAddress + ":" + clientSocket.remotePort );
		}
		
		private function onClientSocketData( event:ProgressEvent ):void
		{
			var buffer:ByteArray = new ByteArray();
			clientSocket.readBytes( buffer, 0, clientSocket.bytesAvailable );
			log( "Received: " + buffer.toString() );
		}

		private function bind( event:Event ):void
		{
			if( serverSocket.bound ) 
			{
				serverSocket.close();
				serverSocket = new ServerSocket();
				
			}
			serverSocket.bind( parseInt( localPort.text ), localIP.text );
			serverSocket.addEventListener( ServerSocketConnectEvent.CONNECT, onConnect );
			serverSocket.listen();
			log( "Bound to: " + serverSocket.localAddress + ":" + serverSocket.localPort );
		}
		
		private function send( event:Event ):void
		{
			try
			{
				if( clientSocket != null && clientSocket.connected )
				{
					clientSocket.writeUTFBytes( message.text );
					clientSocket.flush(); 
					log( "Sent message to " + clientSocket.remoteAddress + ":" + clientSocket.remotePort );
				}
				else log("No socket connection.");
			}
			catch ( error:Error )
			{
				log( error.message );
			}
		}

		private function log( text:String ):void
		{
			logField.appendText( text + "\n" );
			logField.scrollV = logField.maxScrollV;
			trace( text );
		}

		private function setupUI():void
		{
			localIP = createTextField( 10, 10, "Local IP", "0.0.0.0");
			localPort = createTextField( 10, 35, "Local port", "0" );
			createTextButton( 170, 60, "Bind", bind );
			message = createTextField( 10, 85, "Message", "Lucy can't drink milk." );
			createTextButton( 170, 110, "Send", send );
			logField = createTextField( 10, 135, "Log", "", false, 200 )
			
			this.stage.nativeWindow.activate();
		}
		
		private function createTextField( x:int, y:int, label:String, defaultValue:String = '', editable:Boolean = true, height:int = 20 ):TextField
		{
			var labelField:TextField = new TextField();
			labelField.text = label;
			labelField.type = TextFieldType.DYNAMIC;
			labelField.width = 100;
			labelField.x = x;
			labelField.y = y;
			
			var input:TextField = new TextField();
			input.text = defaultValue;
			input.type = TextFieldType.INPUT;
			input.border = editable;
			input.selectable = editable;
			input.width = 280;
			input.height = height;
			input.x = x + labelField.width;
			input.y = y;
			
			this.addChild( labelField );
			this.addChild( input );
			
			return input;
		}
		
		private function createTextButton( x:int, y:int, label:String, clickHandler:Function ):TextField
		{
			var button:TextField = new TextField();
			button.htmlText = "<u><b>" + label + "</b></u>";
			button.type = TextFieldType.DYNAMIC;
			button.selectable = false;
			button.width = 180;
			button.x = x;
			button.y = y;
			button.addEventListener( MouseEvent.CLICK, clickHandler );
			
			this.addChild( button );
			return button;
		}		
	}
}