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

Language Reference only       
DatagramSocket 
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.DatagramSocket
InheritanceDatagramSocket Inheritance EventDispatcher Inheritance Object

Runtime Versions:  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



Properties
 PropertyDefined By
  bound : Boolean
[read-only] Indicates whether this socket object is currently bound to a local address and port.
DatagramSocket
  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
  isSupported : Boolean
[static] [read-only] Indicates whether or not DatagramSocket features are supported in the run-time environment.
DatagramSocket
  localAddress : String
[read-only] The IP address this socket is bound to on the local machine.
DatagramSocket
  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
  remoteAddress : String
[read-only] The IP address of the remote machine to which this socket is connected.
DatagramSocket
  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
  
bind(localPort:int = 0, localAddress:String = "0.0.0.0"):void
Binds this socket to the specified local address and port.
DatagramSocket
  
close():void
Closes the socket.
DatagramSocket
  
connect(remoteAddress:String, remotePort:int):void
Connects the socket to a specified remote address and port.
DatagramSocket
 Inherited
dispatchEvent(event:Event):Boolean
Dispatches an event into the event flow.
EventDispatcher
 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
  
receive():void
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
  
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
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
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
  Dispatched when this socket receives an I/O error.DatagramSocket
Property Detail

bound

property
bound:Boolean  [read-only]

Runtime Versions:  2

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

See also

connected

property 
connected:Boolean  [read-only]

Runtime Versions:  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.

See also

isSupported

property 
isSupported:Boolean  [read-only]

Runtime Versions:  2

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

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

remoteAddress

property 
remoteAddress:String  [read-only]

Runtime Versions:  2

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

See also

remotePort

property 
remotePort:int  [read-only]

Runtime Versions:  2

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

See also

Constructor Detail

DatagramSocket

()Constructor
public function DatagramSocket()

Runtime Versions:  2

Creates a DatagramSocket object.


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

bind

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

Runtime Versions:  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

close

()method 
public function close():void

Runtime Versions:  2

Closes the socket.

The socket is disconnected from the remote machine and unbound from the local machine. A closed socket cannot 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.

connect

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

Runtime Versions:  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.

receive

()method 
public function receive():void

Runtime Versions:  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.

send

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

Runtime Versions:  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

close

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

Runtime Versions:  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.

data

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

Runtime Versions:  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
property IOErrorEvent.type = flash.events.IOErrorEvent.IOERROR

Runtime Versions:  2.5

Dispatched when this socket receives an I/O error.

Examples

<html>
    <head>
    <title>DNSResolver Example</title>
    <script src="AIRAliases.js"></script> 
    <script>
    var datagramSocket = new air.DatagramSocket();
    
    var localIP;
    var localPort;
    var logField;
    var targetIP;
    var targetPort;
    var message;
    
    function init()
    {
        localIP = document.getElementById("localIP");
        localPort = document.getElementById("localPort");
        targetIP = document.getElementById("targetIP");
        targetPort = document.getElementById("targetPort");
        message = document.getElementById("message");
        logField = document.getElementById("logField");
    }

    function bind( event )
    {
    if( datagramSocket.bound ) 
    {
        datagramSocket.close();
        datagramSocket = new air.DatagramSocket();
    }
        datagramSocket.bind( parseInt( localPort.text ), localIP.text );
        datagramSocket.addEventListener( air.DatagramSocketDataEvent.DATA, dataReceived );
        datagramSocket.receive();
        log( "Bound to: " + datagramSocket.localAddress + ":" + datagramSocket.localPort );
    }

    function dataReceived( event )
    {
        //Read the data from the datagram
        log("Received from " + event.srcAddress + ":" + event.srcPort + "> " + 
            event.data.readUTFBytes( event.data.bytesAvailable ) );
    }
    
    function send( event )
    {
        //Send a datagram to the target
        try
        {
        //Create a message in a ByteArray
            var data = new air.ByteArray();
            data.writeUTFBytes( message.value );
            datagramSocket.send( data, 0, 0, targetIP.value, targetPort.value ); 
            log( "Sent message to " + targetIP.value + ":" + targetPort.value );
        }
        catch ( error )
        {
            log( error.message );
        }
    }
        
    function log( text )
    {
        logField.value += text + "\n";
        air.trace( text );
    }

    </script>
    <body onload="init()">
        Local IP <input type="text" id="localIP" value="0.0.0.0"/> 
        Port <input type="text" id="localPort" size="5" value="0"/> 
        <button onclick="bind()">Bind</button><br/>
        <hr/>
        Remote IP <input type="text" id="targetIP" value="127.0.0.1"/> 
        Port <input type="text" id="targetPort" size="5" value="8989"/> <br/>
        Message <input type="text" id="message" size="30" value="Lucy can't drink milk."/> 
        <button onclick="send()">Send</button><br/>
        <textarea id="logField" cols="80" rows="40" title="Log"></textarea>
    </body>
</html>