Hi. Me and my partner have one last project due for our Advanced Java course. It's fairly simple program(In theroy) that has us create a gui that sends data to a server we created and sends back a calculated result on the data. the code sometimes works in that we get a value back to the client. But we get exceptions on the server but can't for the life of us figure out why. Could someone take a look at our code and see whats the matter?
Thanks in advance.
Investment Server
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