20-CS-694 Advanced Programming Techniques Spring 2012
Networking

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

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

Datagram Server

The example span this slide and the next shows how a client assembles a datagram packet, sends it to a server, how the server sends a response to a client. Any datagram packet received by the server is considered a request for the current date and time. The response is encoded as a human readable ascii string, inserted into a packet and sent to the initiator.

Start the server by clicking the "Start Server" button. Get a date by clicking the "Get Next Date" button in the client.

import java.awt.*;
import java.io.*;
import java.net.*;
import java.util.*;
import java.awt.event.*;
import java.applet.*;
import javax.swing.*;

class DatagramServerThread extends Thread {
   DatagramServer server;
   DatagramSocket socket = null;
   TextArea textin, textout;
   TextField status;

   DatagramServerThread(DatagramServer server) {
      super("DatagramServer");
      this.server = server;
      
      try {
         socket = new DatagramSocket(8189);
         server.status.setText("Serving port: " + socket.getLocalPort());
      }
      catch (java.net.SocketException e) {
         server.status.setText("Could not create datagram socket.");
      }
   }

   public void run() {
      if (socket == null) return;

      while (true) {
         try {
            byte[] buf = new byte[256];
            DatagramPacket packet;
            InetAddress address;
            int port;
            String dString = null;

            // receive request
            packet = new DatagramPacket(buf, 256);
            socket.receive(packet);
            address = packet.getAddress();
            port = packet.getPort();
            server.textin.append("From "+String.valueOf(address)+", "+String.valueOf(port)+"\n");

            // send response
            while (true) {
               try { Thread.sleep(1000); } catch (Exception e) { }
               dString = new Date().toString();
               server.textout.append(dString+"\n");
               buf = dString.getBytes();
               packet = new DatagramPacket(buf, buf.length, address, port);
               socket.send(packet);
            }
         }
         catch (Exception e) {
            server.status.setText("Exception:  " + String.valueOf(e));
         }
      }
   }
   
   protected void finalize() {
      if (socket != null) {
         socket.close();
         socket = null;
         server.status.setText("Closing datagram socket.");
      }
   }
}

public class DatagramServer extends Applet implements ActionListener {
   JTextArea textin, textout;
   JTextField status;
   JButton sb;
    
   public void init () {
      setLayout(new BorderLayout());
      Panel p = new Panel();
      p.setLayout(new GridLayout(2,1,10,10));
      Panel q = new Panel();
      q.setLayout(new BorderLayout());
      q.add("North", new JLabel("Receiving"));
      q.add ("Center", new JScrollPane(textin = new JTextArea(10,30)));
      p.add(q);
      q = new Panel();
      q.setLayout(new BorderLayout());
      q.add("North", new JLabel("Sending"));
      q.add("Center", new JScrollPane(textout = new JTextArea(10,30)));
      p.add(q);
      add("Center", p);
       
      p = new Panel();
      p.setLayout(new BorderLayout());
      p.add("Center", status = new JTextField(20));
      p.add("East", sb = new JButton("Start Server"));
      add("South", p);
   }

   public void start () {
      sb.addActionListener(this);
   }
   
   public void actionPerformed (ActionEvent evt) {
      if (evt.getSource() == sb) {
         new DatagramServerThread(this).start();
      }
   }
}