Java Reference
In-Depth Information
5. Accept the sender's address and port from the packet.
Methods getAddress and getPort of our DatagramPacket object are used for this.
For example:
InetAddress clientAddress = inPacket.getAddress();
int clientPort = inPacket.getPort();
6. Retrieve the data from the buffer.
For convenience of handling, the data will be retrieved as a string, using an over-
loaded form of the String constructor that takes three arguments:
a byte array;
the start position within the array (= 0 here);
the number of bytes (= full size of buffer here).
For example:
String message = new String(inPacket.getData(),
7. Create the response datagram.
Create a DatagramPacket object, using an overloaded form of the constructor that
takes four arguments:
the byte array containing the response message;
the size of the response;
the client's address;
the client's port number.
The fi rst of these arguments is returned by the getBytes method of the String
class (acting on the desired String response). For example:
DatagramPacket outPacket =
new DatagramPacket(response.getBytes(),
response.length(),clientAddress, clientPort);
(Here, response is a String variable holding the return message.)
8. Send the response datagram.
This is achieved by calling method send of our DatagramSocket object, supplying
our outgoing DatagramPacket object as an argument. For example:
Steps 4-8 may be executed indefi nitely (within a loop).
Under normal circumstances, the server would probably not be closed down at
all. However, if an exception occurs, then the associated DatagramSocket should be
closed, as shown in step 9 below.
9. Close the DatagramSocket.
This is effected simply by calling method close of our DatagramSocket object. For
Search WWH ::

Custom Search