// Fig. 16.6: Client.java
// Set up a Client that will send packets to a
// server and receive packets from a server.
import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
import com.deitel.jhtp2.ch11.CloseWindowAndExit;

public class Client extends Frame implements ActionListener {
   private TextField enter;
   private TextArea display;

   private DatagramPacket sendPacket, receivePacket;
   private DatagramSocket socket;

   public Client()
   {
      super( "Client" );
      enter = new TextField( "Type message here" );
      enter.addActionListener( this );
      add( enter, BorderLayout.NORTH );
      display = new TextArea();
      add( display, BorderLayout.CENTER );
      setSize( 400, 300 );
      setVisible( true );

      try {
         socket = new DatagramSocket();
      }
      catch( SocketException se ) {
         se.printStackTrace();
         System.exit( 1 );
      }
   }

   public void waitForPackets()
   {
      while ( true ) {
         try {
            // set up packet
            byte data[] = new byte[ 100 ];
            receivePacket =
               new DatagramPacket( data, data.length );

            // wait for packet
            socket.receive( receivePacket );
 
            // process packet
            display.append( "\nPacket received:" +
               "\nFrom host: " + receivePacket.getAddress() +
               "\nHost port: " + receivePacket.getPort() +
               "\nLength: " + receivePacket.getLength() +
               "\nContaining:\n\t" +
               new String( receivePacket.getData() ) );
         }
         catch( IOException exception ) {
            display.append( exception.toString() + "\n" );
            exception.printStackTrace();
         }
      }
   }

   public void actionPerformed( ActionEvent e )
   {
      try {
         display.append( "\nSending packet containing: " +
                         e.getActionCommand() + "\n" );

         String s = e.getActionCommand();
         byte data[] = s.getBytes();

         sendPacket = new DatagramPacket( data, data.length,
            InetAddress.getLocalHost(), 5000 );
         socket.send( sendPacket );
         display.append( "Packet sent\n" );
      }
      catch ( IOException exception ) {
         display.append( exception.toString() + "\n" );
         exception.printStackTrace();
      }
   }

   public static void main( String args[] )
   {
      Client c = new Client();

      c.addWindowListener( new CloseWindowAndExit() );
      c.waitForPackets();
   }
}