Java Reference
In-Depth Information
7. Retrieve the data from the buffer.
This is the same as step 6 in the server program. For example:
String response =
new String(inPacket.getData(),0,
inPacket.getLength());
Steps 2-7 may then be repeated as many times as required.
8. Close the DatagramSocket.
This is the same as step 9 in the server program. For example:
datagramSocket.close();
As was the case in the server code, there is no checked exception generated by the
above close method in the fi nally clause of the client program, so there will be no
try block. In addition, since there is no inter-message connection maintained
between client and server, there is no protocol required for closing down the dialogue.
This means that we do not wish to send the fi nal '***CLOSE***' string (though we
shall continue to accept this from the user, since we need to know when to stop
sending messages at the client end). The line of code (singular, this time) corresponding
to each of the above steps will be indicated via an emboldened comment.
Now for the code itself…
import java.io.*;
import java.net.*;
import java.util.*;
public class UDPEchoClient
{
private static InetAddress host;
private static fi nal int PORT = 1234;
private static DatagramSocket datagramSocket;
private static DatagramPacket inPacket, outPacket;
private static byte[] buffer;
public static void main(String[] args)
{
try
{
host = InetAddress.getLocalHost();
}
catch(UnknownHostException uhEx)
{
System.out.println("Host ID not found!");
System.exit(1);
}
Search WWH ::




Custom Search