Object Serialization to and from Servlet

This is an extensive example that illustrates several additional features.

First, it involves comuniction between and applet client and a servlet server inf which an object is written to the socket, and then read and returned by the servlet.

Second, the object that is sent back and forth includes a transient variable that is not written when the object is sent but rather restored when it is read back in.


 

The Content Object

import java.io.*;
import java.util.*;

public class jbsCSCO extends Object implements Serializable {

        String msg = null;
        private transient long timeMillis;
        private transient Date date;

        public jbsCSCO ()  {
            super ();
            timeMillis = System.currentTimeMillis ();
            date = new Date ( timeMillis );
        }  // end constructor

        public void setMsg ( String s )  {
            msg = s;
        }  // end setMsg ()

        public String getMsg ()  {
            return ( msg );
        }  // end getMsg ()


        public Date getDate ()  {
            return ( date );
        }  // end getDate ()

       private void readObject ( ObjectInputStream in ) throws IOException, ClassNotFoundException  {
            in.defaultReadObject ();
            timeMillis = System.currentTimeMillis ();
            date = new Date ( timeMillis );
        }  // end readObject


}  // end jbsCSCO

The Client Applet

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

public class jbsClientAppletCO extends Applet implements ActionListener, WindowListener {

//*****  Mulit-threaded client, sends and receives multiple messages
//       expected to connect to server on jbs.cs.unc.edu:8903


protected String DEFAULT_HOST = "jbspc.cs.unc.edu";
protected int DEFAULT_PORT = 8903;
String host;
int port;

jbsAppletConnectServerCO connection;

Frame outerBox;
TextField hostDisplay, portDisplay;
TextArea logDisplay, sendDisplay, recvDisplay;
Panel topPanel;
Panel middlePanel;
Panel buttonPanel;
Button connectButton, sendButton, cancelButton, quitButton;


// ************** init

    public void init ()  {

        buildUI ();

    }  // end init



//***********  Interface Methods   ***********


//****  ActionListener methods

  public void actionPerformed ( ActionEvent e )  {

    Object s = e.getSource();

    // *** process Button actions

    if ( s instanceof Button )  {

        if ( s == connectButton )  {
            connection = new jbsAppletConnectServerCO ( this );
            connection.start ();
        }  // end connectButton

        if ( s == sendButton )  {
            connection.sendReceive ();
        }  // end sendButton

        if ( s == cancelButton )  {
            sendDisplay.setText ( "" );
        }  // end cancelButton

        if ( s == quitButton )  {
            logDisplay.appendText ( "Closing connection and quitting\n" );
            connection.closeConnection ();
            try {Thread.sleep ( 2000 );} catch ( InterruptedException except) {;}

            outerBox.hide ();
            outerBox.dispose ();
            System.exit ( 0 );

            }  // end quitButton

    }  // end process Button actions

  }  // end actionPerformed


//****  WindowListener methods

  public void windowActivated ( WindowEvent e )  {
  }

  public void windowDeactivated ( WindowEvent e )  {
  }

  public void windowOpened ( WindowEvent e )  {
  }

   public void windowClosed ( WindowEvent e )  {
  }

  public void windowClosing ( WindowEvent e )  {
    outerBox.hide ();
    outerBox.dispose ();
    System.exit(0);
  }

  public void windowIconified ( WindowEvent e )  {
  }

  public void windowDeiconified ( WindowEvent e )  {
  }


//***********  Utility Methods   ***********

// **************  buildUI

  private void buildUI ()  {

    String hostString, portString;

    hostString = getParameter ( "host" );
    portString = getParameter ( "port" );

    if ( hostString == null ) {
        hostDisplay = new TextField ( DEFAULT_HOST  , 30 );
    }  else  {
        hostDisplay = new TextField ( hostString, 30 );
    }
    if ( portString == null ) {
        portDisplay = new TextField ( Integer.toString ( DEFAULT_PORT ), 30 );
    }  else  {
        portDisplay = new TextField ( portString, 4 );
    }

    topPanel = new Panel ();
    topPanel.setLayout ( new GridLayout ( 2, 1 ) );
    topPanel.add ( hostDisplay );
    topPanel.add ( portDisplay );

    logDisplay = new TextArea ( 40, 10 );

    sendDisplay = new TextArea ( 40, 5 );
    recvDisplay = new TextArea ( 40, 5 );
    sendDisplay.setText ("Default message.");
    recvDisplay.setText ("Messages received will be displayed here.");
    middlePanel = new Panel ();
    middlePanel.setLayout ( new GridLayout ( 3, 1 ) );
    middlePanel.add ( logDisplay );
    middlePanel.add ( sendDisplay );
    middlePanel.add ( recvDisplay );

    connectButton = new Button ( "Connect" );
    sendButton = new Button ( "Send" );
    cancelButton = new Button ( "Cancel" );
    quitButton = new Button ( "Quit" );
    connectButton.addActionListener ( this );
    sendButton.addActionListener ( this );
    cancelButton.addActionListener ( this );
    quitButton.addActionListener ( this );
    buttonPanel = new Panel ( );
    buttonPanel.add ( connectButton );
    buttonPanel.add ( sendButton );
    buttonPanel.add ( cancelButton );
    buttonPanel.add ( quitButton );

    outerBox = new Frame ("Client_Applet");
    outerBox.addWindowListener ( this );
    outerBox.add ( "North", topPanel );
    outerBox.add ( "Center", middlePanel );
    outerBox.add ( "South", buttonPanel );

    outerBox.resize ( 400, 450 );
    outerBox.show ();

    }  // end buildUI


}  // end jbsClientAppletCO
//******************************************
class jbsAppletConnectServerCO extends Thread implements Serializable {

jbsClientAppletCO source;

String host;
int port;
Socket connection;

InputStream inStream;
ObjectInputStream inObjectStream;
OutputStream outStream;
ObjectOutputStream outObjectStream;

jbsCSCO msgObject;
String message;
Date date;
int hour, minute, second;
long time;

// **************  jbsAppletConnectServer

    jbsAppletConnectServerCO ( jbsClientAppletCO c)  {

        super ();

        source = (jbsClientAppletCO ) c;

        connectServer ();

    }  // end constructor


// **************  run

    public void run  ()  {

    }  // end run


// **************  connectServer

  public void connectServer (  )  {

    host = source.hostDisplay.getText ();
    if ( host.equals ("" ) ) host = source.DEFAULT_HOST;
    if ( ! ( source.portDisplay.getText () ).equals ( "" ) ) port = Integer.parseInt ( source.portDisplay.getText () );
    else port = source.DEFAULT_PORT;
    source.logDisplay.setText ( "Server specified: "+host+":"+port+"\n\n" );


    try  {

      connection = new Socket ( host, port );

      outStream = connection.getOutputStream ();
      outObjectStream = new ObjectOutputStream ( outStream );
      inStream = connection.getInputStream ();
      inObjectStream = new ObjectInputStream ( inStream );

      source.logDisplay.appendText ( "Socket created: \n  connecting to server "+host+":"+port+"\n\n" );

    }  // end try

    catch ( Exception except)  {
      source.logDisplay.setText ( "Error connecting to server\n" );
      except.printStackTrace ();
      System.exit ( 1 );
    }  // end catch

  }  // end connectServer



  public void sendReceive ()  {

    try {

        message = source.sendDisplay.getText ();
        msgObject = new jbsCSCO ();
        msgObject.setMsg ( message );
        date = msgObject.getDate ();
        hour = date.getHours();
        minute = date.getMinutes();
        second = date.getSeconds();
        time = date.getTime();

        outObjectStream.writeObject ( msgObject );
        outObjectStream.flush();

        source.logDisplay.appendText ( "Message, below, sent to Server at: "+hour+" : "+minute+" : "+second+" : "+time+"\n" );
        source.recvDisplay.setText ( "Awaiting Message Object." );
        source.recvDisplay.setForeground ( Color.red );

        msgObject = (jbsCSCO)inObjectStream.readObject ();

        message = msgObject.getMsg ();

        date = msgObject.getDate ();
        hour = date.getHours();
        minute = date.getMinutes();
        second = date.getSeconds();
        time = date.getTime();

        source.recvDisplay.setText ( message );
        source.logDisplay.appendText ( "Message returned from Server at:   "+hour+" : "+minute+" : "+second+" : "+time+"\n\n" );

    }  // end try for input

    catch ( EOFException except ) {
        source.logDisplay.appendText ( "EOF received\n" );
        closeConnection ();
    }  // end catch IOException
    catch ( IOException e )  {
        source.logDisplay.appendText ( "IOException\n" );
        e.printStackTrace ();
        return;
    }  // end catch IOException
    catch ( ClassNotFoundException e )  {
        source.logDisplay.appendText ( "ClassNotFoundException\n" );
        e.printStackTrace ();
        return;
    }  // end catch IOException

  }  // end sendReceive

// **************

  public void closeConnection () {

    try {
      connection.close ();
     }  catch ( IOException except )  {
        source.logDisplay.appendText ( "  Error clossing conncetion\n" );
       except.printStackTrace ();
     }

  }  // end closeConnection


}  // end jbsAppletConnectServerCO

The Servlet

import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class jbsServerThreadedCO extends HttpServlet {


//*****  Mulit-threaded server, accepts multiple messages
//       default runs on jbs.cs.unc.edu:8903

public boolean firsttime = true;
String host;
int port;
protected String DEFAULT_HOST = "jbspc.cs.unc.edu";
protected int DEFAULT_PORT = 8903;
jbsListenServerCO listen;

    public void doGet (HttpServletRequest req, HttpServletResponse resp)
	throws ServletException, IOException
	{

        if ( firsttime )  {
            firsttime = false;
            setHostPort ( req );
            returnHTML ( resp );
            listen = new jbsListenServerCO ( port );
            listen.start ();
        }  // end firsttime
        else  {
            returnHTML ( resp );
        }  // end else

    }  // end doGet


    public void setHostPort ( HttpServletRequest res )  {

        try {
            InetAddress here = InetAddress.getLocalHost ();
            host = here.getHostName ();
        }  // end try
        catch (UnknownHostException e)
        { ;}

        port = DEFAULT_PORT;
        String qs = res.getQueryString ();
        if ( qs == null ) return;
        Hashtable ht = HttpUtils.parseQueryString ( qs );
        String portString[] = (String[])ht.get( "port" );
        if ( portString[0] != null ) {
            port = Integer.parseInt( portString[0] );
        }  // end if

    }  // end setHostPort

    public void returnHTML ( HttpServletResponse resp )  {

    ServletOutputStream out;

        try  {

	        resp.setContentType("text/html");
	        out = resp.getOutputStream();

	        out.println("<html>");
	        out.println("<head><title>jbsServerThreadedCO</title></head>");
	        out.println("<body>");
	        out.println("<center><font color=AA0000>");
	        out.println("<h3>jbsServerThreadedCO Running on Host " + host + ", port " + Integer.toString (port) + "</h3>");
	        out.println("<h3>Applet Tag for jbsClientAppletCO Returned</h3>");
	        out.println("</font></center>");
	        out.println("<applet code=jbsClientAppletCO.class codebase=http://" + host + ":8080/Courses/wwwp-s98/applets/jbsClientAppletCO width=50 height=50>");
	        out.println("<param name=host value=" + host +">");
	        out.println("<param name=port value=" + Integer.toString(port) +">");
	        out.println("</applet>");
	        out.println("</body>");
	        out.println("</html>");
	        out.flush();
	        out.close();
	    }  // end try
        catch ( IOException except)  {
        }  // end catch

    }  // end returnHTML


}  // end ServerThreadedCO
//*****************************************
class jbsListenServerCO extends Thread  {

jbsServerThreadedCO source;
ServerSocket listenSocket;
int port;
Socket connection;
jbsHandleServerCO handle;
boolean again = true;


// **************  jbsListenServer

    jbsListenServerCO ( int p)  {
        super ();
        port = p;
    }  // end constructor


// **************  run

    public void run  ()  {

        try  {
            listenSocket = new ServerSocket ( port );
            while ( true )  {
                Socket connection = listenSocket.accept();
                jbsHandleServerCO handleServer = new jbsHandleServerCO ( connection );
                handleServer.start ();
            }  // end while

    }  catch ( IOException e )  {
    }  // end catch


}  // end run


}  // end jbsListenServerCO
//*****************************************
class jbsHandleServerCO extends Thread implements Serializable  {

Socket connection;

InputStream inStream;
ObjectInputStream inObjectStream;
OutputStream outStream;
ObjectOutputStream outObjectStream;

Object msgObject;


// **************  jbsHandleServerCO

    jbsHandleServerCO ( Socket socket )  {
        super ();
        connection =  socket;
    }  // end constructor


// **************  run

    public void run  ()  {

        try  {
            outStream = connection.getOutputStream ();
            outObjectStream = new ObjectOutputStream ( outStream );
            inStream = connection.getInputStream ();
            inObjectStream = new ObjectInputStream ( inStream );

            while ( true )  {

                msgObject = (Object)inObjectStream.readObject ();

                outObjectStream.writeObject ( msgObject );

            }  // end while

        }  // end try

        catch ( EOFException except ) {
            try  {
                connection.close ();
                return;
            }
            catch ( IOException e )  {
                return;
            }  // end IOException

         }  // end catch EOFException
         catch ( IOException e )  {
            this.destroy ();
            return;
         }  // end catch IOException
         catch ( ClassNotFoundException e )  {
            System.out.println("ClassNotFoundException error");
            e.printStackTrace();
            return;
         }  // end catch IOException


    }  // end run


}  // end jbsHandleServer

Run the Servlet ( jbspc )

Run the Servlet (wwwj )