Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 1 of 1

Thread: Exceptions with my simple Client and server programs

  1. #1
    Junior Member
    Join Date
    Dec 2009
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Exceptions with my simple Client and server programs

    Hi, me and a partner aare working on our last project for our advanced java class and have hit a stumbling block. We basically have to java programs, one is a server that recieves the data we send it from the client, calculates a interest value and returns it back to the client. The client shows a GUI that allows the user to specify this data and send it out to the server. What we have sort of works right now, but the server keeps getting a couple exceptions when we send data to it and we can't for the life of us figure out whats wrong. Could someone please check our code and see whats the matter? I think the problem lies in the server as that's where the exceptions have popped up in.

    Investment Client
    import java.io.*;
    import java.net.*;
    import java.util.*;
    import java.io.EOFException;
    import java.io.IOException;
    import java.text.DateFormat;
    import java.util.Date;
    import java.awt.*;
    import javax.swing.*;
     
    public class InvestmentServer extends JFrame
    {
       // Text area for displaying contents
       private JTextArea jta = new JTextArea();
     
       private Socket connectToClient;
       private BufferedReader isFromClient;
       private PrintWriter osToClient;
     
       public void runServer1 ()
       {
    	  // Place text area on the frame
    	  setLayout(new BorderLayout());
    	  add(new JScrollPane(jta), BorderLayout.CENTER);
     
    	  setTitle("InvestmentServer");
    	  setSize(500, 300);
    	  setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    	  setVisible(true);
     
          try
          {
              // Step 1: create a server socket
             ServerSocket serverSock = new ServerSocket(9000);
     
             //create a date/time and format
             Date today = new Date();
             DateFormat formatter = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG);
     
             //output date/time
             System.out.println("InvestmentServer started at " + formatter.format(today));
     
    	 	  // start listening for clients connection on the server socket
             connectToClient = serverSock.accept();
     
             // use buffer reader stream to get data from client
             isFromClient =
                        new BufferedReader(new InputStreamReader(
    			               connectToClient.getInputStream()));
     
    	 	 //create buffer writer to send data to client
             osToClient = new PrintWriter(connectToClient.getOutputStream(), true);
     
    	 	 // continuously get data from client and send back result
     
             boolean cont = true;
             while(cont == true)
             {
                StringTokenizer st = new StringTokenizer
                    (isFromClient.readLine());
     
    	        // convert data from client to a double or int
                double investmentAmount = new Double(st.nextToken()).doubleValue();
                System.out.println(investmentAmount);
                int years = new Integer(st.nextToken()).intValue();
                double interestRate = new Double(st.nextToken()).doubleValue();
     
                System.out.println("Investment amount received from client: "+investmentAmount);
                System.out.println("Number of years received from client: "+years);
                System.out.println("Annual interst rate received from client: "+interestRate);
     
                if (investmentAmount < 0 || years < 0 || interestRate < 0)
                {
                   cont = false;
                   System.out.println("invalid data");
    		    }
                else
                {
                   double result = (investmentAmount * Math.pow((interestRate/12+1.0),years*12));
                   System.out.println(" future value calculated: "+ result);
                   osToClient.println(result);
                }
             }
             osToClient.println(-99);
             System.out.println("%%%%%Server is exiting%%%%%%%");
          }
          catch(IOException e1)
          {
             System.err.println("Server died with excption: " + e1.toString());
             System.exit(0);
          }
    	  finally
          {
    		closeConnection();
    	  }//end finally
     
        } // end runServer1
     
     
    	private void closeConnection()
    	{
    	  try
    	  {
    	    osToClient.close();       //close output stream
    	    isFromClient.close();     //close input stream
    	    connectToClient.close();  //close socket
          } //end try
     
          catch (IOException ioException)
          {
    		ioException.printStackTrace();
    	  } // end catch
     
     
    	}// end closeConnection
     
     
     
    //----------------------------------------------
       public static void main(String[] args)
       {
         // declare a server1 object
         InvestmentServer server1 = new InvestmentServer();
         server1.runServer1();
       }//end main method
     
    }//end class

    Investment Client

    import java.io.*;
    import java.net.*;
    import java.util.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.text.*;
     
    import java.io.EOFException;
    import java.io.IOException;
     
    public class InvestmentClient extends JFrame implements ActionListener
    {
    	private Socket connectToServer;
    	private BufferedReader stdin;
    	private BufferedReader isFromServer;
    	private PrintWriter osToServer;
     
    	// Text fields for Investment amount, years, interest rate, and result
    	private JTextField jtfInvestAmount, jtfYears, jtfInterest, jtfResult;
     
    	// Buttons "Calculate and "Clear"
    	private JButton jbtCalc, jbtClear;
     
    	// Menu items "Calculate", Exit"
        private JMenuItem jmiCalc, jmiExit, jmiAbout;
     
        /** Default constructor */
    	public InvestmentClient()
    	{
    		setTitle("Future Investment Value");
     
    	    // Create menu bar
    	    JMenuBar jmb = new JMenuBar();
     
    	    // Set menu bar to the frame
    	    setJMenuBar(jmb);
     
    	    // Add menu "Operation" to menu bar
    	    JMenu operationMenu = new JMenu("Operation");
    	    jmb.add(operationMenu);
     
    	    // Add menu "Help" in menu bar
    	    JMenu helpMenu = new JMenu("Help");
    	    jmb.add(helpMenu);
    	    helpMenu.add(jmiAbout = new JMenuItem("About"));
     
    	    // Add menu items to menu "Operation"
    	    operationMenu.add(jmiCalc= new JMenuItem("Calculate"));
    	    operationMenu.addSeparator();
    	    operationMenu.add(jmiExit = new JMenuItem("Exit"));
     
    	    // Panel p1 to hold text fields and labels
    	    JPanel p1 = new JPanel();
    	    p1.setLayout(new GridLayout(4, 2, 30, 5));
     
    	    p1.add(new JLabel("Investment Amount"));
    	    p1.add(jtfInvestAmount = new JTextField(10));
    	    p1.add(new JLabel("Years"));
    	    p1.add(jtfYears = new JTextField(10));
    	    p1.add(new JLabel("Annual Interest Rate"));
    	    p1.add(jtfInterest = new JTextField(10));
    	    p1.add(new JLabel("Future value"));
    	    p1.add(jtfResult = new JTextField(10));
    	    jtfResult.setEditable(false);
     
    	    // Panel p2 to hold buttons
    	    JPanel p2 = new JPanel();
    	    p2.setLayout(new FlowLayout());
    	    p2.add(jbtCalc = new JButton("Calculate"));
    	    p2.add(jbtClear = new JButton("Clear"));
     
    	    // Add panels to the frame
    	    getContentPane().setLayout(new BorderLayout());
    	    getContentPane().add(p1, BorderLayout.NORTH);
    	    getContentPane().add(p2, BorderLayout.SOUTH);
     
    	    // Register listeners
    	    jbtCalc.addActionListener(this);
    	    jbtClear.addActionListener(this);
    	    jmiAbout.addActionListener(this);
    	    jmiCalc.addActionListener(this);
    	    jmiExit.addActionListener(this);
     
    	    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    	    pack();
    	 	setVisible(true);
     
     
    	}//end Default Constructor
     
     
     
    	//---------------------------------------------------------
    	public void sendData()
    	{
    		try
    		{
    			// create a client socket Use this to generate the error
    			// message:  "Client died with exception: "
    			// Socket serverSock = new Socket("localhost",8000);
    			// Note the server is on port 9000 not 8000.
    			//Step 1: create a client socket to connnect to the server
     
    			connectToServer = new Socket("localhost",9000);
     
    			stdin = new BufferedReader(new InputStreamReader(System.in), 1);
     
    			//Step 2: use buffer reader stream to get data from server
    			isFromServer = new BufferedReader(new InputStreamReader
    					       (connectToServer.getInputStream()));
     
    			//Step 2: create buffer writer to send data to server
    			osToServer = new PrintWriter
                				(connectToServer.getOutputStream(), true);
     
    			// send data to server (Investment, years and interest rate)
    			String test = jtfInvestAmount.getText() + " " +
    							   jtfYears.getText() + " " +
    							   jtfInterest.getText();
     
    			osToServer.println(test);
     
    			//get data from server (Future Value)
    			StringTokenizer st = new StringTokenizer
    		                     (isFromServer.readLine());
     
    			// display in result.
            	jtfResult.setText(st.nextToken());
    		}
     
            catch(IOException e1)
    		{
    			System.err.println("Client died with exception: " + e1.toString());
     
    			System.exit(0);
          	}//end catch
    		finally
          	{
    	    	//Close the connection
            	closeConnection();
    	  	}// end finally
    	}//end runClient
     
     
    	private void closeConnection ()
    	{
     
    		try
    	 	{
    			osToServer.close();    //Close output stream
    		  	isFromServer.close();  // Close input stream
    		  	connectToServer.close(); //Close socket
    		} //end try
    		catch (IOException ioException)
            {
    			ioException.printStackTrace();
    		} //end catch
    	} //end closeConnection
     
     
    	//--------------------------------------------------------------------
    	/** Handle ActionEvent from buttons and menu items
        * @param e the ActionEvent either button press, or menu selection
        */
        public void actionPerformed(ActionEvent e)
        {
     
    		String actionCommand = e.getActionCommand();
     
           	// Handle button events
           	if (e.getSource() instanceof JButton)
           	{
             	if ("Calculate".equals(actionCommand))
                	sendData();
             	else if ("Clear".equals(actionCommand))
                	clear();
           	}// end if instanceof JButton
           	else if (e.getSource() instanceof JMenuItem)
           	{
             	// Handle menu item events
             	if ("Calculate".equals(actionCommand))
                	sendData();
             	else if ("Exit".equals(actionCommand))
                	System.exit(0);
             	else if ("About".equals(actionCommand))
                	JOptionPane.showMessageDialog(null,
                				"Compute Future Investment Value",
                                "About This Program", JOptionPane.INFORMATION_MESSAGE);
           	}//end if instanceof JMenuItem
      	} // end actionPerformed method
     
     
        /** Clears all data fields */
        private void clear()
        {
          	jtfInvestAmount.setText("");
          	jtfYears.setText("");
          	jtfInterest.setText("");
          	jtfResult.setText("");
        }//end clear method
     
     
       //--------------------------------------------------------
     
       public static void main(String[] args)
       {
    	   	//declare a client1 object
     
    	 	InvestmentClient client1 = new InvestmentClient();
     
    	 	// close the connection.
    	 	//client1.closeConnection();
     
       } //end main
     
     
       //---------------------------------------------------------
     
    }// end class

    Thanks in advance for any help.

    EDIT: oh and here is the exceptions we get.
    Exception in thread "main" java.lang.NullPointerException
    at java.util.StringTokenizer.<init>(StringTokenizer.j ava:182)
    at java.util.StringTokenizer.<init>(StringTokenizer.j ava:219)
    at InvestmentServer.runServer1(InvestmentServer.java: 70)
    at InvestmentServer.main(InvestmentServer.java:134)
    Last edited by Dko; December 12th, 2009 at 11:46 PM.


Similar Threads

  1. Replies: 2
    Last Post: November 19th, 2009, 11:55 PM
  2. Simple server-client trouble
    By DC200 in forum Java Networking
    Replies: 3
    Last Post: November 12th, 2009, 08:16 AM
  3. Download a file to client from server
    By mvittalreddy in forum Java Networking
    Replies: 4
    Last Post: October 5th, 2009, 04:23 AM
  4. instead of printing in the client, report get printed in the server
    By jmvenkat in forum Java Theory & Questions
    Replies: 0
    Last Post: September 19th, 2009, 01:30 AM
  5. Replies: 1
    Last Post: April 20th, 2009, 11:17 AM