4. Datagrams

The UDP protocol provides a mode of network communication whereby applications send packets of data, called datagrams to one another:

4.1.1. Definition

A datagram is an independent, self-contained message sent over the network whose arrival, arrival time, and content are not guaranteed.

4.1.2. Java classes

  • DatagramPacket class;

  • DatagramSocket class.

4.2.1. The Quote server

It waits for Datagram requests for quotes ans servers them in Datagram packets. Three classes implement the application:

  • QuoteServer

  • QuoteServerThread.

  • QuoteClient.

4.2.2. The QuoteServer Class

Just calls the server thread:

class QuoteServer {
    public static void main(String[] args) {
        new QuoteServerThread().start();
    }
}

Audio in Portuguese

4.2.3. The QuoteServerThread Class

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);

Audio in Portuguese

4.2.4. The QuoteClient Class

  • 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);

4.2.5. Run the Client

Quote of the Moment: Life is wonderful. Without it we'd all be dead.

Audio in Portuguese