Java Reference
In-Depth Information
System . out . println ( "There are " + dp . getLength ()
+ " bytes of data in the packet" );
System . out . println (
new String ( dp . getData (), dp . getOffset (), dp . getLength (), "UTF-8" ));
} catch ( UnknownHostException | UnsupportedEncodingException ex ) {
System . err . println ( ex );
}
}
}
Here's the output:
% java DatagramExample
This packet is addressed to www.ibiblio.org/152.2.254.81 on port 7
There are 15 bytes of data in the packet
This is a test.
The setter Methods
Most of the time, the six constructors are sufficient for creating datagrams. However,
Java also provides several methods for changing the data, remote address, and remote
port after the datagram has been created. These methods might be important in a sit‐
uation where the time to create and garbage collect new DatagramPacket objects is a
significant performance hit. In some situations, reusing objects can be significantly
faster than constructing new ones: for example, in a networked twitch game that sends
a datagram for every bullet fired or every centimeter of movement. However, you would
have to use a very speedy connection for the improvement to be noticeable relative to
the slowness of the network itself.
public void setData(byte[] data)
The setData() method changes the payload of the UDP datagram. You might use this
method if you are sending a large file (where large is defined as “bigger than can com‐
fortably fit in one datagram”) to a remote host. You could repeatedly send the same
DatagramPacket object, just changing the data each time.
public void setData(byte[] data, int offset, int length)
This overloaded variant of the setData() method provides an alternative approach to
sending a large quantity of data. Instead of sending lots of new arrays, you can put all
the data in one array and send it a piece at a time. For instance, this loop sends a large
array in 512-byte chunks:
int offset = 0 ;
DatagramPacket dp = new DatagramPacket ( bigarray , offset , 512 );
int bytesSent = 0 ;
while ( bytesSent < bigarray . length ) {
socket . send ( dp );
bytesSent += dp . getLength ();
int bytesToSend = bigarray . length - bytesSent ;
Search WWH ::




Custom Search