Java Reference
In-Depth Information
To illustrate the above procedure and to allow easy comparison with the equivalent
TCP/IP code, the example from Sect. 2.2.1 will be employed again. As before, the
lines of code corresponding to each of the above steps are indicated via emboldened
comments. Note that the numMessages part of the message that is returned by the
server is somewhat artifi cial, since, in a real-world application, many clients could be
making connection and the overall message numbers would not mean a great deal to
individual clients. However, the cumulative message-numbering will serve to empha-
sise that there are no separate sockets for individual clients.
There are two other differences from the equivalent TCP/IP code that are worth
noting, both concerning the possible exceptions that may be generated:
￿ the IOException in main is replaced with a SocketException ;
￿ there is no checked exception generated by the close method in the fi nally
clause, so there is no try block.
Now for the code…
//Server that echoes back client's messages.
//At end of dialogue, sends message indicating number of
//messages received. Uses datagrams.
public class UDPEchoServer
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)
System.out.println("Opening port…\n");
datagramSocket =
new DatagramSocket(PORT);
//Step 1.
catch(SocketException sockEx)
System.out.println("Unable to open port!");
Search WWH ::

Custom Search