| | |
Unable to populate String.
Please support our Java advertiser: Programming Forums - DaniWeb Sister Site
Thread Solved |
•
•
Join Date: Aug 2008
Posts: 13
Reputation:
Solved Threads: 0
Hello,
I am creating a client/server application that verifies math equations for addition, subtraction, and division. I think I just need someone else’s eyes to possibly see where I am going wrong with this. Everything seems to be working fine except for one variable. This is the String serverAnswer variable in my Server class. When I debug the application, the serverAnswer variable remains null, can anyone tell me what I’m doing wrong? I wrote the code for where it should be populated in the processConnection() method of my server class. I know this is a lot of code, but it is needed to debug the application. Thank you.
I am creating a client/server application that verifies math equations for addition, subtraction, and division. I think I just need someone else’s eyes to possibly see where I am going wrong with this. Everything seems to be working fine except for one variable. This is the String serverAnswer variable in my Server class. When I debug the application, the serverAnswer variable remains null, can anyone tell me what I’m doing wrong? I wrote the code for where it should be populated in the processConnection() method of my server class. I know this is a lot of code, but it is needed to debug the application. Thank you.
Java Syntax (Toggle Plain Text)
import java.io.EOFException; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.ServerSocket; import java.net.Socket; import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JFrame; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.SwingUtilities; import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import javax.script.ScriptException; import java.lang.*; import sun.io.Converters; import javax.script.*; public class Server extends JFrame { private JTextField enterField; // inputs message from user private JTextArea displayArea; // display information to user private ObjectOutputStream output; // output stream to client private ObjectInputStream input; // input stream from client private ServerSocket server; // server socket private Socket connection; // connection to client private int counter = 1; // counter of number of connections String serverAnswer; //private String serverAnswer; // set up GUI public Server() { super( "Server" ); enterField = new JTextField(); // create enterField enterField.setEditable( false ); enterField.addActionListener( new ActionListener() { // send message to client public void actionPerformed( ActionEvent event ) { sendData( event.getActionCommand() ); enterField.setText( "" ); } // end method actionPerformed } // end anonymous inner class ); // end call to addActionListener add( enterField, BorderLayout.NORTH ); displayArea = new JTextArea(); // create displayArea add( new JScrollPane( displayArea ), BorderLayout.CENTER ); setSize( 300, 150 ); // set size of window setVisible( true ); // show window } // end Server constructor // set up and run server public void runServer() { try // set up server to receive connections; process connections { server = new ServerSocket( 12345, 100 ); // create ServerSocket while ( true ) { try { waitForConnection(); // wait for a connection getStreams(); // get input & output streams processConnection(); // process connection } // end try catch ( EOFException eofException ) { displayMessage( "\nServer terminated connection" ); } // end catch finally { closeConnection(); // close connection counter++; } // end finally } // end while } // end try catch ( IOException ioException ) { ioException.printStackTrace(); } // end catch } // end method runServer // wait for connection to arrive, then display connection info private void waitForConnection() throws IOException { displayMessage( "Waiting for connection\n" ); connection = server.accept(); // allow server to accept connection displayMessage( "Connection " + counter + " received from: " + connection.getInetAddress().getHostName() ); } // end method waitForConnection // get streams to send and receive data private void getStreams() throws IOException { // set up output stream for objects output = new ObjectOutputStream( connection.getOutputStream() ); output.flush(); // flush output buffer to send header information // set up input stream for objects input = new ObjectInputStream( connection.getInputStream() ); displayMessage( "\nGot I/O streams\n" ); } // end method getStreams // process connection with client private void processConnection() throws IOException { String message = "Connection successful"; sendData( message ); // send connection successful message // enable enterField so server user can send messages setTextFieldEditable( false ); ScriptEngine engine = new ScriptEngineManager().getEngineByExtension("js"); do // process messages sent from client { try // read message and display it { message = ( String ) input.readObject(); // read new message if (message.contains("+")){ Object result = engine.eval(message); serverAnswer = String.valueOf(result); } else if(message.contains("/")){ Object result = engine.eval(message); serverAnswer = String.valueOf(result); } else if(message.contains("-")){ Object result = engine.eval(message); serverAnswer = String.valueOf(result); } else if (message.equals(serverAnswer)){ displayMessage("\n" + "You are correct"); } else{ displayMessage("\n" + "Incorrect!"); } //displayMessage("\n" + serverAnswer); } catch (ScriptException e) { // Something went wrong e.printStackTrace(); } catch (ClassNotFoundException classNotFoundException){ displayMessage ( "\nUnknown object type received" ); } displayMessage( "\n" + message ); // display message } // end try /* catch ( ClassNotFoundException classNotFoundException ) { displayMessage( "\nUnknown object type received" ); } // end catch } */while ( !message.equals( "CLIENT>>> TERMINATE" ) ); } // end method processConnection // close streams and socket private void closeConnection() { displayMessage( "\nTerminating connection\n" ); setTextFieldEditable( false ); // disable enterField try { output.close(); // close output stream input.close(); // close input stream connection.close(); // close socket } // end try catch ( IOException ioException ) { ioException.printStackTrace(); } // end catch } // end method closeConnection // send message to client private void sendData( String message ) { try // send object to client { output.writeObject( "SERVER>>> " + message ); output.flush(); // flush output to client displayMessage( "\nSERVER>>> " + message ); } // end try catch ( IOException ioException ) { displayArea.append( "\nError writing object" ); } // end catch } // end method sendData // manipulates displayArea in the event-dispatch thread private void displayMessage( final String messageToDisplay ) { SwingUtilities.invokeLater( new Runnable() { public void run() // updates displayArea { displayArea.append( messageToDisplay ); // append message } // end method run } // end anonymous inner class ); // end call to SwingUtilities.invokeLater } // end method displayMessage // manipulates enterField in the event-dispatch thread private void setTextFieldEditable( final boolean editable ) { SwingUtilities.invokeLater( new Runnable() { public void run() // sets enterField's editability { enterField.setEditable( editable ); } // end method run } // end inner class ); // end call to SwingUtilities.invokeLater } // end method setTextFieldEditable } // end class Server
Java Syntax (Toggle Plain Text)
import javax.swing.JFrame; public class ServerTest { public static void main( String args[] ) { Server application = new Server(); // create server application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); application.runServer(); // run server application } // end main } // end class ServerTest
Java Syntax (Toggle Plain Text)
import java.io.EOFException; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.InetAddress; import java.net.Socket; import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JFrame; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.SwingUtilities; import javax.swing.JLabel; public class Client extends JFrame { private JTextField equationField; // enter equation here private JTextField answerField;//enter answer here private JTextArea displayArea; // display information to user private ObjectOutputStream output; // output stream to server private ObjectInputStream input; // input stream from server private String message = ""; // message from server private String chatServer; // host server for this application private Socket client; // socket to communicate with server private JLabel label;//direction label // initialize chatServer and set up GUI public Client( String host ) { super( "Client" ); chatServer = host; // set server to which this client connects /* label = new JLabel("Enter equation above and answer below.");//create label add (label, BorderLayout.NORTH); */ equationField = new JTextField(); // create enterField equationField.setEditable( false ); equationField.addActionListener( new ActionListener() { // send message to server public void actionPerformed( ActionEvent event ) { sendData( event.getActionCommand() ); equationField.setText( "" ); } // end method actionPerformed } // end anonymous inner class ); // end call to addActionListener add( equationField, BorderLayout.NORTH); answerField = new JTextField(); // create enterField answerField.setEditable( false ); answerField.addActionListener( new ActionListener() { // send message to server public void actionPerformed( ActionEvent event ) { sendData( event.getActionCommand() ); answerField.setText( "" ); } // end method actionPerformed } // end anonymous inner class ); // end call to addActionListener add( answerField, BorderLayout.SOUTH ); displayArea = new JTextArea(); // create displayArea add( new JScrollPane( displayArea ), BorderLayout.CENTER); setSize( 500, 250 ); // set size of window setVisible( true ); // show window } // end Client constructor // connect to server and process messages from server public void runClient() { try // connect to server, get streams, process connection { connectToServer(); // create a Socket to make connection getStreams(); // get the input and output streams processConnection(); // process connection } // end try catch ( EOFException eofException ) { displayMessage( "\nClient terminated connection" ); } // end catch catch ( IOException ioException ) { ioException.printStackTrace(); } // end catch finally { closeConnection(); // close connection } // end finally } // end method runClient // connect to server private void connectToServer() throws IOException { displayMessage( "Attempting connection\n" ); // create Socket to make connection to server client = new Socket( InetAddress.getByName( chatServer ), 12345 ); displayMessage("Enter equation in top field and answer in the bottom field\n"); // display connection information displayMessage( "Connected to: " + client.getInetAddress().getHostName() ); } // end method connectToServer // get streams to send and receive data private void getStreams() throws IOException { // set up output stream for objects output = new ObjectOutputStream( client.getOutputStream() ); output.flush(); // flush output buffer to send header information // set up input stream for objects input = new ObjectInputStream( client.getInputStream() ); displayMessage( "\nGot I/O streams\n" ); } // end method getStreams // process connection with server private void processConnection() throws IOException { // enable enterField so client user can send messages setTextFieldEditable( true ); do // process messages sent from server { try // read message and display it { message = ( String ) input.readObject(); // read new message displayMessage( "\n" + message ); // display message } // end try catch ( ClassNotFoundException classNotFoundException ) { displayMessage( "\nUnknown object type received" ); } // end catch } while ( !message.equals( "SERVER>>> TERMINATE" ) ); } // end method processConnection // close streams and socket private void closeConnection() { displayMessage( "\nClosing connection" ); setTextFieldEditable( false ); // disable enterField try { output.close(); // close output stream input.close(); // close input stream client.close(); // close socket } // end try catch ( IOException ioException ) { ioException.printStackTrace(); } // end catch } // end method closeConnection // send message to server private void sendData( String message ) { try // send object to server { output.writeObject( "CLIENT>>> " + message ); output.flush(); // flush data to output displayMessage( "\nCLIENT>>> " + message ); } // end try catch ( IOException ioException ) { displayArea.append( "\nError writing object" ); } // end catch } // end method sendData // manipulates displayArea in the event-dispatch thread private void displayMessage( final String messageToDisplay ) { SwingUtilities.invokeLater( new Runnable() { public void run() // updates displayArea { displayArea.append( messageToDisplay ); } // end method run } // end anonymous inner class ); // end call to SwingUtilities.invokeLater } // end method displayMessage // manipulates enterField in the event-dispatch thread private void setTextFieldEditable( final boolean editable ) { SwingUtilities.invokeLater( new Runnable() { public void run() // sets enterField's editability { equationField.setEditable( editable ); answerField.setEditable(editable); } // end method run } // end anonymous inner class ); // end call to SwingUtilities.invokeLater } // end method setTextFieldEditable } // end class Client
Java Syntax (Toggle Plain Text)
import javax.swing.JFrame; public class ClientTest { public static void main( String args[] ) { Client application; // declare client application // if no command line args if ( args.length == 0 ) application = new Client( "127.0.0.1" ); // connect to localhost else application = new Client( args[ 0 ] ); // use args to connect application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); application.runClient(); // run client application } // end main } // end class ClientTest
•
•
Join Date: Nov 2008
Posts: 332
Reputation:
Solved Threads: 54
Java Syntax (Toggle Plain Text)
private void processConnection() throws IOException { String message = "Connection successful"; ... message = (String) input.readObject(); // read new message displayMessage("\n|" + message + "|"); ///"CLIENT>>> " TO REMOVE! message = message.substring(10); ...
![]() |
Similar Threads
- Firefox and chained select menus (JavaScript / DHTML / AJAX)
- Help me !!! its urgent (VB.NET)
- Error encountered while searching for data from access table (Visual Basic 4 / 5 / 6)
- Need Help in debugging this code. (C)
- Saving Excel Spreadsheet using ADO.net gives inconsistent results (C#)
Other Threads in the Java Forum
- Previous Thread: Need to write postfix to a file
- Next Thread: Newbie: Can't see why my loop doesn't work!
| Thread Tools | Search this Thread |
Tag cloud for Java
affinetransform android api apple applet application arc arguments array arrays automation binary bluetooth businessintelligence chat class classes client code component database desktop draw ebook eclipse encode equation error event exception file fractal game givemetehcodez graphics gui helpwithhomework html ide image input integer intersect j2me java javaexcel javaprojects jmf jni jpanel julia linked linux list loop mac main map method methods mobile netbeans newbie number object open-source oracle parameter print problem program programming project properties recursion reference replaysolutions rotatetext scanner score screen scrollbar server set size sms socket sort sql string superclass swing template test threads time tree windows working xstream





