The UDP protocol provides a mode of network communication whereby applications send packets of data, called datagrams to one another:
A datagram is an independent, self-contained message sent over the network whose arrival, arrival time, and content are not guaranteed.
It waits for Datagram requests for quotes ans servers them in Datagram packets. Three classes implement the application:
QuoteServer
QuoteServerThread.
QuoteClient.
Just calls the server thread:
class QuoteServer { public static void main(String[] args) { new QuoteServerThread().start(); } }
The QuoteServerThread constructor:
QuoteServerThread() { super("QuoteServer"); try { socket = new DatagramSocket(); System.out.println("QuoteServer listening on port: " + socket.getLocalPort()); } catch (java.net.SocketException e) { System.err.println("Could not create datagram socket."); } this.openInputFile(); }
The run() method's infinite loop:
Section that receives requests:
packet = new DatagramPacket(buf, 256); socket.receive(packet); address = packet.getAddress(); port = packet.getPort();
Section that construct the responses:
if (qfs == null) dString = new Date().toString(); else dString = getNextQuote(); dString.getBytes(0, dString.length(), buf, 0); packet = new DatagramPacket(buf, buf.length, address, port); socket.send(packet);
The main() method for the client application:
int port; InetAddress address; DatagramSocket socket = null; DatagramPacket packet; byte[] sendBuf = new byte[256]; if (args.length != 2) { System.out.println("Usage: java DatagramClient <hostname> <port#>"); return; }
The client program sends a request to the server:
address = InetAddress.getByName(args[0]); port = Integer.parseInt(args[1]); packet = new DatagramPacket(sendBuf, 256, address, port); socket.send(packet); System.out.println("Client sent request packet.");
The client gets a response from the server:
packet = new DatagramPacket(sendBuf, 256); socket.receive(packet); String received = new String(packet.getData(), 0); System.out.println("Client received packet: " + received);
Quote of the Moment: Life is wonderful. Without it we'd all be dead.
Copyright © 1998-2009 Dilvan Moreira