Package | flash.net |
Class | public class DatagramSocket |
Inheritance | DatagramSocket EventDispatcher Object |
Language Version: | ActionScript 3.0 |
Runtime Versions: | AIR 2 |
AIR profile support: This feature is supported on
all desktop operating systems, but is not supported on mobile devices or AIR for TV devices. You can test for
support at run time using the DatagramSocket.isSupported
property. See
AIR Profile Support for more information regarding API support across multiple profiles.
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.
More examples
Learn more
Related API Elements
Property | Defined 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 | ||
constructor : 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 | ||
prototype : 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 |
Method | Defined By | ||
---|---|---|---|
Creates a DatagramSocket object. | DatagramSocket | ||
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 | ||
Binds this socket to the specified local address and port. | DatagramSocket | ||
Closes the socket. | DatagramSocket | ||
Connects the socket to a specified remote address and port. | DatagramSocket | ||
Dispatches an event into the event flow. | EventDispatcher | ||
Checks whether the EventDispatcher object has any listeners registered for a specific type
of event. | EventDispatcher | ||
Indicates whether an object has a specified property defined. | Object | ||
Indicates whether an instance of the Object class is in the prototype chain of the object specified
as the parameter. | Object | ||
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 | ||
Removes a listener from the EventDispatcher object. | EventDispatcher | ||
Sends packet containing the bytes in the ByteArray using UDP. | DatagramSocket | ||
Sets the availability of a dynamic property for loop operations. | Object | ||
Returns the string representation of this object, formatted according to locale-specific conventions. | Object | ||
Returns the string representation of the specified object. | Object | ||
Returns the primitive value of the specified object. | Object | ||
Checks whether an event listener is registered with this EventDispatcher object or any of
its ancestors for the specified event type. | EventDispatcher |
Event | Summary | Defined By | ||
---|---|---|---|---|
[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 | |||
[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 |
bound | property |
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
Related API Elements
isSupported | property |
localAddress | property |
localPort | property |
remoteAddress | property |
remotePort | property |
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.
|
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:
| |
Error — This error occurs when localAddress is not a valid local address.
|
Example ( How to use this example )
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
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 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
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.
|
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: — 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
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:
| |
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.
|
close | Event |
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.
Event.CLOSE
constant defines the value of the type
property of a close
event object.
This event has the following properties:
Property | Value |
---|---|
bubbles | false |
cancelable | false ; there is no default behavior to cancel. |
currentTarget | The object that is actively processing the Event object with an event listener. |
target | The object whose connection has been closed. |
data | Event |
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 thetype
property of a data
event object.
ioError | Event |
flash.events.IOErrorEvent
property IOErrorEvent.type =
flash.events.IOErrorEvent.IOERROR
Language Version: | ActionScript 3.0 |
Runtime Versions: | AIR 2.5 |
Dispatched when this socket receives an I/O error.
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; } } }
Mon Nov 28 2011, 06:48 AM -08:00