Java Reference
In-Depth Information
2.3.1 DatagramPacket
Instead of sending and receiving streams of bytes as with TCP, UDP endpoints exchange
self-contained messages, called datagrams, which are represented in Java as instances of
DatagramPacket . To send, a Java program constructs a DatagramPacket instance and passes it as
an argument to the send() method of a DatagramSocket . To receive, a Java program constructs
a DatagramPacket instance with preallocated space (a byte[ ] ), into which the contents of a
received message can be copied (if/when one arrives), and then passes the instance to the
receive() method of a DatagramSocket .
In addition to the data, each instance of DatagramPacket also contains address and port
information, the semantics of which depend on whether the datagram is being sent or received.
When a DatagramPacket is sent, the address and port identify the destination; for a received
DatagramPacket , they identify the source of the received message. Thus, a server can receive
into a DatagramPacket instance, modify its buffer contents, then send the same instance, and
the modified message will go back to its origin. Internally, a DatagramPacket also has length
and offset fields, which describe the location and number of bytes of message data inside the
associated buffer. See the following reference and Section 2.3.4 for some pitfalls to avoid when
using DatagramPacket s.
DatagramPacket
Constructors
DatagramPacket ( byte[ ] buffer , int length )
DatagramPacket ( byte[ ] buffer , int offset , int length )
DatagramPacket ( byte[ ] buffer , int length , InetAddress remoteAddr , int remotePort )
DatagramPacket ( byte[ ] buffer , int offset , int length , InetAddress remoteAddr , int re-
motePort )
Constructs a datagram and makes the given byte array its data buffer. The first two
forms are typically used to construct DatagramPackets for receiving because the desti-
nation address is not specified (although it could be specified later with setAddress()
and setPort() ). The second two forms are typically used to construct DatagramPackets
for sending.
buffer
Datagram payload
length
Number of bytes of the buffer that will actually be used.
If the datagram is sent, length bytes will be transmitted. If
receiving into this datagram, length specifies the maximum
number of bytes to be placed in the buffer.
offset
Location in the buffer array of the first byte of message data
to be sent/received; defaults to 0 if unspecified.
 
Search WWH ::




Custom Search