Adobe® Flex® 4 Language Reference
Show Packages and Classes List |  Packages  |  Classes  |  Index  |  Appendixes
flash.net 
DatagramSocket 
Packageflash.net
Classpublic class DatagramSocket
InheritanceDatagramSocket Inheritance EventDispatcher Inheritance Object

Language Version: ActionScript 3.0
Runtime Versions: AIR 2

The DatagramSocket class enables code to send and receive Universal Datagram Protocol (UDP) packets.

Datagram packets are individually transmitted between the source and destination. Packets can arrive in a different order than they were sent. Packets lost in transmission are not retransmitted, or even detected.

Data sent using a datagram socket is not automatically broken up into packets of transmittable size. If you send a UDP packet that exceeds the maximum transmission unit (MTU) size, network discards the packet (without warning). The limiting MTU is the smallest MTU of any interface, switch, or router in the transmission path. You can use the NetworkInterface class to determine the MTU of the local interface, but other nodes in the network can have different MTU values.

The Socket class uses TCP which provides guaranteed packet delivery and automatically divides and reassembles large packets. TCP also provides better network bandwidth management. These features mean that data sent using a TCP socket incurs higher latency, but for most uses, the benefits of TCP far outweigh the costs. Most network communication should use the Socket class rather than the DatagramSocket class.

The DatagramSocket class is useful for working with applications where a small transmission latency is important and packet loss is tolerable. For example, network operations in voice-over-IP (VoIP) applications and real-time, multiplayer games can often benefit from UDP. The DatagramSocket class is also useful for some server-side applications. Since UDP is a stateless protocol, a server can handle more requests from more clients than it can with TCP.

The DatagramSocket 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



Public Properties
 PropertyDefined By
  AIR-only bound : Boolean
[read-only] Indicates whether this socket object is currently bound to a local address and port.
DatagramSocket
  AIR-only connected : Boolean
[read-only] Indicates whether this socket object is currently connected to a remote address and port.
DatagramSocket
 Inheritedconstructor : Object
A reference to the class object or constructor function for a given object instance.
Object
  AIR-only isSupported : Boolean
[static] [read-only] Indicates whether or not DatagramSocket features are supported in the run-time environment.
DatagramSocket
  AIR-only localAddress : String
[read-only] The IP address this socket is bound to on the local machine.
DatagramSocket
  AIR-only localPort : int
[read-only] The port this socket is bound to on the local machine.
DatagramSocket
 Inheritedprototype : Object
[static] A reference to the prototype object of a class or function object.
Object
  AIR-only remoteAddress : String
[read-only] The IP address of the remote machine to which this socket is connected.
DatagramSocket
  AIR-only remotePort : int
[read-only] The port on the remote machine to which this socket is connected.
DatagramSocket
Public Methods
 MethodDefined By
  
Creates a DatagramSocket object.
DatagramSocket
 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
  
AIR-only bind(localPort:int = 0, localAddress:String = "0.0.0.0"):void
Binds this socket to the specified local address and port.
DatagramSocket
  
Closes the socket.
DatagramSocket
  
AIR-only connect(remoteAddress:String, remotePort:int):void
Connects the socket to a specified remote address and port.
DatagramSocket
 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
 Inherited
Indicates whether the specified property exists and is enumerable.
Object
  
Enables this DatagramSocket object to receive incoming packets on the bound IP address and port.
DatagramSocket
 Inherited
removeEventListener(type:String, listener:Function, useCapture:Boolean = false):void
Removes a listener from the EventDispatcher object.
EventDispatcher
  
AIR-only send(bytes:ByteArray, offset:uint = 0, length:uint = 0, address:String = null, port:int = 0):void
Sends packet containing the bytes in the ByteArray using UDP.
DatagramSocket
 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
 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 operating system closes this socket.DatagramSocket
  Dispatched when this socket receives a packet of data.DatagramSocket
 Inherited[broadcast event] Dispatched when the Flash Player or AIR application operating loses system focus and is becoming inactive.EventDispatcher
  DatagramSocket
Property Detail
AIR-only 

bound

property
bound:Boolean  [read-only]

Language Version: ActionScript 3.0
Runtime Versions: AIR 2

Indicates whether this socket object is currently bound to a local address and port.



Implementation
    public function get bound():Boolean

See also

AIR-only 

connected

property 
connected:Boolean  [read-only]

Language Version: ActionScript 3.0
Runtime Versions: AIR 2

Indicates whether this socket object is currently connected to a remote address and port.

Note: A value of true does not mean that a remote computer is listening on the connected address and port. It only means that this DataGramSocket object will only send data to or receive data from that address and port.



Implementation
    public function get connected():Boolean

See also

AIR-only 

isSupported

property 
isSupported:Boolean  [read-only]

Language Version: ActionScript 3.0
Runtime Versions: AIR 2

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



Implementation
    public static function get isSupported():Boolean
AIR-only 

localAddress

property 
localAddress:String  [read-only]

Language Version: ActionScript 3.0
Runtime Versions: AIR 2

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



Implementation
    public function get localAddress():String

See also

AIR-only 

localPort

property 
localPort:int  [read-only]

Language Version: ActionScript 3.0
Runtime Versions: AIR 2

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



Implementation
    public function get localPort():int

See also

AIR-only 

remoteAddress

property 
remoteAddress:String  [read-only]

Language Version: ActionScript 3.0
Runtime Versions: AIR 2

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



Implementation
    public function get remoteAddress():String

See also

AIR-only 

remotePort

property 
remotePort:int  [read-only]

Language Version: ActionScript 3.0
Runtime Versions: AIR 2

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



Implementation
    public function get remotePort():int

See also

Constructor Detail
AIR-only 

DatagramSocket

()Constructor
public function DatagramSocket()

Language Version: ActionScript 3.0
Runtime Versions: AIR 2

Creates a DatagramSocket object.


Throws
SecurityError — if content outside the AIR application security sandbox attempts to create a DatagramSocket object.
Method Detail

AIR-only bind

()method
public function bind(localPort:int = 0, localAddress:String = "0.0.0.0"):void

Language Version: ActionScript 3.0
Runtime Versions: AIR 2

Binds this socket to the specified local address and port.

The bind() method executes synchronously. The bind operation completes before the next line of code is executed.

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.
 
IOError — This error occurs if the socket cannot be bound, such as when:
  1. localPort is already in use by another socket.
  2. the user account under which the application is running doesn't have sufficient system privileges to bind to the specified port. (Privilege issues typically occur when localPort < 1024.)
  3. This DatagramSocket object is already bound.
  4. This DatagramSocket object has been closed.
 
Error — This error occurs when localAddress is not a valid local address.

Example  ( How to use this example )

The following example illustrates various ways to bind a DatagramSocket object:

udpSocket.bind(); //bind to any available port, listen on all IPv4 addresses
udpSocket.bind( 0, "0.0.0.0" ); //same as above
udpSocket.bind( 0, "127.0.0.1" ); //any available port on the localhost address
udpSocket.bind( 8989, "192.168.0.1" ); //port 8989 on a particular IPv4 address
udpSocket.bind( 0, "::" ); //any available port on all IPv6 address
udpSocket.bind( 8989, "::1" ); //port 8989 on the IPv6 localhost address
udpSocket.bind( 8989, "2001:1890:110b:1e19:f06b:72db:7026:3d7a" ); //port 8989 on a particular IPv6 address

AIR-only close

()method 
public function close():void

Language Version: ActionScript 3.0
Runtime Versions: AIR 2

Closes the socket.

The socket is disconnected from the remote machine and unbound from the local machine. A closed socket can be reused.


Throws
IOError — If the socket cannot be closed (because of an internal, networking, or operating system error), or if the socket is not open.

AIR-only connect

()method 
public function connect(remoteAddress:String, remotePort:int):void

Language Version: ActionScript 3.0
Runtime Versions: AIR 2

Connects the socket to a specified remote address and port.

When a datagram socket is "connected," datagram packets can only be sent to and received from the specified target. Packets from other sources are ignored. Connecting a datagram socket is not required. Establishing a connection can remove the need to filter out extraneous packets from other sources. However, a UDP socket connection is not a persistent network connection (as it is for a TCP connection). It is possible that the remote end of the socket does not even exist.

If the bind() method has not been called, the socket is automatically bound to the default local address and port.

Parameters

remoteAddress:String — The IP address of the remote machine with which to establish a connection. This address can be an IPv4 or IPv6 address. If bind() has not been called, the address family of the remoteAddress, IPv4 or IPv6, is used when calling the default bind().
 
remotePort:int — The port number on the remote machine used to establish a connection.


Throws
RangeError — This error occurs when localPort is less than 1 or greater than 65535.
 
ArgumentError — This error occurs when localAddress is not a syntactically valid address. Or when a default route address ('0.0.0.0' or '::') is used.
 
IOError — This error occurs if the socket cannot be connected, such as when bind() has not been called before the call to connect() and default binding to the remote address family is not possible.

AIR-only receive

()method 
public function receive():void

Language Version: ActionScript 3.0
Runtime Versions: AIR 2

Enables this DatagramSocket object to receive incoming packets on the bound IP address and port.

The function returns immediately. The DatagramSocket object dispatches a data event when a data packet is received.


Events
data:DatagramSocketDataEvent — when a UDP packet is received.

AIR-only send

()method 
public function send(bytes:ByteArray, offset:uint = 0, length:uint = 0, address:String = null, port:int = 0):void

Language Version: ActionScript 3.0
Runtime Versions: AIR 2

Sends packet containing the bytes in the ByteArray using UDP.

If the socket is connected, the packet is sent to the remote address and port specified in the connect() method and no destination IP address and port can be specified. If the socket is not connected, the packet is sent to the specified address and port and you must supply valid values for address and port. If the bind() method has not been called, the socket is automatically bound to the default local address and port.

Note: Sending data to a broadcast address is not supported.

Parameters

bytes:ByteArray — a ByteArray containing the packet data.
 
offset:uint (default = 0) — The zero-based offset into the bytes ByteArray object at which the packet begins.
 
length:uint (default = 0) — The number of bytes in the packet. The default value of 0 causes the entire ByteArray to be sent, starting at the value specified by the offset parameter.
 
address:String (default = null) — The IPv4 or IPv6 address of the remote machine. An address is required if one has not already been specified using the connect() method.
 
port:int (default = 0) — The port number on the remote machine. A value greater than 0 and less than 65536 is required if the port has not already been specified using the connect() method.


Throws
RangeError — This error occurs when port is less than 1 or greater than 65535.
 
ArgumentError — If the socket is not connected and address is not a well-formed IP address.
 
IOError — This error occurs:
  1. If bind() has not been called, and when default binding to the destination address family is not possible.
  2. On some operating systems, an IOError is thrown if the connect() method is called when an ICMP "destination unreachable" message has already been received from the target host. (Thus, the error is thrown on the second failed attempt to send data, not the first.) Other operating systems, such as Windows, disregard these ICMP messages, so no error is thrown.
 
Error — when the bytes parameter is null.
 
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.
 
IllegalOperationError — If the address or port parameters are specified when the socket has already been connected.
Event Detail
AIR-only 

close

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

Language Version: ActionScript 3.0
Runtime Versions: AIR 2

Dispatched when the operating system closes this socket.

The close event is not dispatched when the DatagramSocket close() method is called.

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.
AIR-only 

data

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

Language Version: ActionScript 3.0
Runtime Versions: AIR 2

Dispatched when this socket receives a packet of data.

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

ioError

Event  
Event Object Type: flash.events.IOErrorEvent

DatagramSocketExample.as

package
{
    import flash.display.Sprite;
    import flash.events.DatagramSocketDataEvent;
    import flash.events.Event;
    import flash.events.MouseEvent;
    import flash.events.TimerEvent;
    import flash.net.DatagramSocket;
    import flash.text.TextField;
    import flash.text.TextFieldAutoSize;
    import flash.text.TextFieldType;
    import flash.utils.ByteArray;
    import flash.utils.Timer;
    
    public class DatagramSocketExample extends Sprite
    {
        private var datagramSocket:DatagramSocket = new DatagramSocket();;

        private var localIP:TextField;
        private var localPort:TextField;
        private var logField:TextField;
        private var targetIP:TextField;
        private var targetPort:TextField;
        private var message:TextField;
        
        public function DatagramSocketExample()
        {
            setupUI();
        }

        private function bind( event:Event ):void
        {
            if( datagramSocket.bound ) 
            {
                datagramSocket.close();
                datagramSocket = new DatagramSocket();
                
            }
            datagramSocket.bind( parseInt( localPort.text ), localIP.text );
            datagramSocket.addEventListener( DatagramSocketDataEvent.DATA, dataReceived );
            datagramSocket.receive();
            log( "Bound to: " + datagramSocket.localAddress + ":" + datagramSocket.localPort );
        }
        
        private function dataReceived( event:DatagramSocketDataEvent ):void
        {
            //Read the data from the datagram
            log("Received from " + event.srcAddress + ":" + event.srcPort + "> " + 
                event.data.readUTFBytes( event.data.bytesAvailable ) );
        }
        
        private function send( event:Event ):void
        {
            //Create a message in a ByteArray
            var data:ByteArray = new ByteArray();
            data.writeUTFBytes( message.text );
            
            //Send a datagram to the target
            try
            {
                datagramSocket.send( data, 0, 0, targetIP.text, parseInt( targetPort.text )); 
                log( "Sent message to " + targetIP.text + ":" + targetPort.text );
            }
            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
        {
            targetIP = createTextField( 10, 10, "Target IP:", "192.168.0.1" );
            targetPort = createTextField( 10, 35, "Target port:", "8989" );
            message = createTextField( 10, 60, "Message:", "Lucy can't drink milk." );
            localIP = createTextField( 10, 85, "Local IP", "0.0.0.0");
            localPort = createTextField( 10, 110, "Local port:", "0" );
            createTextButton( 250, 135, "Bind", bind );
            createTextButton( 300, 135, "Send", send );
            logField = createTextField( 10, 160, "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 = 180;
            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;
            
        }
    }
}