Java Reference
In-Depth Information
fi nally //If exception thrown, close
"\n* Closing connection… *");
datagramSocket.close(); //Step 9.
Setting up the corresponding client requires the eight steps listed below.
1. Create a DatagramSocket object.
This is similar to the creation of a DatagramSocket object in the server program, but
with the important difference that the constructor here requires no argument, since
a default port (at the client end) will be used. For example:
DatagramSocket datagramSocket = new DatagramSocket();
2. Create the outgoing datagram.
This step is exactly as for step 7 of the server program. For example:
DatagramPacket outPacket =
new DatagramPacket(message.getBytes(),
message.length(), host, PORT);
3. Send the datagram message.
Just as for the server, this is achieved by calling method send of the DatagramSocket
object, supplying our outgoing DatagramPacket object as an argument. For example:
Steps 4-6 below are exactly the same as steps 2-4 of the server procedure.
4. Create a buffer for incoming datagrams.
For example:
byte[] buffer = new byte[256];
5. Create a DatagramPacket object for the incoming datagrams.
For example:
DatagramPacket inPacket =
new DatagramPacket(buffer, buffer.length);
6. Accept an incoming datagram.
For example:
Search WWH ::

Custom Search