20-CS-694 Advanced Programming Techniques Spring 2012

Interfaces, Exceptions, Graphics, Animation, Threads, Reflection, Networking, RMI, JDBC, JNI

     Previous     Next     DatagramClient.java     DatagramServer.java      All lectures
                    DatagramSocket Class    DatagramPacket Class    InetAddress Class

Datagram Client

This is the client that connects to the Date server of the previous slide.
import java.awt.*;
import java.io.*;
import java.net.*;
import java.util.*;
import java.awt.event.*;
import java.applet.*;
import javax.swing.*;

public class DatagramClient extends Applet implements ActionListener {
   JButton next;
   JTextArea lines;
   JTextField status;
   public void init () {
      setLayout(new BorderLayout());
      Panel p = new Panel();
      p.setLayout(new BorderLayout());
      p.add("North", new Label("Status"));
      p.add("Center", status = new JTextField(20));
      add("North", p);
      p = new Panel();
      p.setLayout(new BorderLayout());
      p.add("North", new JLabel("Received"));
      p.add("Center", new JScrollPane(lines = new JTextArea(10,30)));
      add("Center", p);
      add("South", next = new JButton("Get Next Date"));
   public void start () {
   public void actionPerformed (ActionEvent evt) {
      if (evt.getSource() == next) doit();
   public void doit () {
      int port;
      InetAddress address;
      DatagramSocket socket;
      DatagramPacket packet;
      byte[] sendBuf = new byte[256];
      String pp, aa;

      pp = getParameter("port");
      aa = getParameter("address");

      status.setText("IP: "+aa+" Port: "+pp);
      try {
         // bind to the socket   
         socket = new DatagramSocket();

         // send request   
         port = Integer.parseInt(pp);
         address = InetAddress.getByName(aa);
         status.setText("Request to "+String.valueOf(address)+", "+String.valueOf(port));
         packet = new DatagramPacket(sendBuf, 256, address, port);

         // get response   
         packet = new DatagramPacket(sendBuf, 256);
         String received = new String(packet.getData());

      } catch (Exception e) {
         status.setText("Trouble Contacting Server - Server Down?");