Unable to populate String.

Please support our Java advertiser: Programming Forums - DaniWeb Sister Site
Thread Solved

Join Date: Aug 2008
Posts: 13
Reputation: AllenB is an unknown quantity at this point 
Solved Threads: 0
AllenB AllenB is offline Offline
Newbie Poster

Unable to populate String.

 
0
  #1
Jan 23rd, 2009
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.

  1. import java.io.EOFException;
  2. import java.io.IOException;
  3. import java.io.ObjectInputStream;
  4. import java.io.ObjectOutputStream;
  5. import java.net.ServerSocket;
  6. import java.net.Socket;
  7. import java.awt.BorderLayout;
  8. import java.awt.event.ActionEvent;
  9. import java.awt.event.ActionListener;
  10. import javax.swing.JFrame;
  11. import javax.swing.JScrollPane;
  12. import javax.swing.JTextArea;
  13. import javax.swing.JTextField;
  14. import javax.swing.SwingUtilities;
  15. import javax.script.ScriptEngine;
  16. import javax.script.ScriptEngineManager;
  17. import javax.script.ScriptException;
  18. import java.lang.*;
  19. import sun.io.Converters;
  20. import javax.script.*;
  21.  
  22. public class Server extends JFrame
  23. {
  24. private JTextField enterField; // inputs message from user
  25. private JTextArea displayArea; // display information to user
  26. private ObjectOutputStream output; // output stream to client
  27. private ObjectInputStream input; // input stream from client
  28. private ServerSocket server; // server socket
  29. private Socket connection; // connection to client
  30. private int counter = 1; // counter of number of connections
  31. String serverAnswer;
  32. //private String serverAnswer;
  33.  
  34. // set up GUI
  35. public Server()
  36. {
  37. super( "Server" );
  38.  
  39. enterField = new JTextField(); // create enterField
  40. enterField.setEditable( false );
  41. enterField.addActionListener(
  42. new ActionListener()
  43. {
  44. // send message to client
  45. public void actionPerformed( ActionEvent event )
  46. {
  47. sendData( event.getActionCommand() );
  48. enterField.setText( "" );
  49. } // end method actionPerformed
  50. } // end anonymous inner class
  51. ); // end call to addActionListener
  52.  
  53. add( enterField, BorderLayout.NORTH );
  54.  
  55. displayArea = new JTextArea(); // create displayArea
  56. add( new JScrollPane( displayArea ), BorderLayout.CENTER );
  57.  
  58. setSize( 300, 150 ); // set size of window
  59. setVisible( true ); // show window
  60. } // end Server constructor
  61.  
  62. // set up and run server
  63. public void runServer()
  64. {
  65. try // set up server to receive connections; process connections
  66. {
  67. server = new ServerSocket( 12345, 100 ); // create ServerSocket
  68.  
  69. while ( true )
  70. {
  71. try
  72. {
  73. waitForConnection(); // wait for a connection
  74. getStreams(); // get input & output streams
  75. processConnection(); // process connection
  76. } // end try
  77. catch ( EOFException eofException )
  78. {
  79. displayMessage( "\nServer terminated connection" );
  80. } // end catch
  81. finally
  82. {
  83. closeConnection(); // close connection
  84. counter++;
  85. } // end finally
  86. } // end while
  87. } // end try
  88. catch ( IOException ioException )
  89. {
  90. ioException.printStackTrace();
  91. } // end catch
  92. } // end method runServer
  93.  
  94. // wait for connection to arrive, then display connection info
  95. private void waitForConnection() throws IOException
  96. {
  97. displayMessage( "Waiting for connection\n" );
  98. connection = server.accept(); // allow server to accept connection
  99. displayMessage( "Connection " + counter + " received from: " +
  100. connection.getInetAddress().getHostName() );
  101. } // end method waitForConnection
  102.  
  103. // get streams to send and receive data
  104. private void getStreams() throws IOException
  105. {
  106. // set up output stream for objects
  107. output = new ObjectOutputStream( connection.getOutputStream() );
  108. output.flush(); // flush output buffer to send header information
  109.  
  110. // set up input stream for objects
  111. input = new ObjectInputStream( connection.getInputStream() );
  112.  
  113. displayMessage( "\nGot I/O streams\n" );
  114. } // end method getStreams
  115.  
  116. // process connection with client
  117. private void processConnection() throws IOException
  118. {
  119.  
  120. String message = "Connection successful";
  121. sendData( message ); // send connection successful message
  122.  
  123.  
  124. // enable enterField so server user can send messages
  125. setTextFieldEditable( false );
  126. ScriptEngine engine = new ScriptEngineManager().getEngineByExtension("js");
  127.  
  128. do // process messages sent from client
  129.  
  130. {
  131. try // read message and display it
  132. {
  133. message = ( String ) input.readObject(); // read new message
  134. if (message.contains("+")){
  135. Object result = engine.eval(message);
  136. serverAnswer = String.valueOf(result);
  137. }
  138. else if(message.contains("/")){
  139. Object result = engine.eval(message);
  140. serverAnswer = String.valueOf(result);
  141. }
  142. else if(message.contains("-")){
  143. Object result = engine.eval(message);
  144. serverAnswer = String.valueOf(result);
  145. }
  146. else if (message.equals(serverAnswer)){
  147. displayMessage("\n" + "You are correct");
  148. }
  149. else{
  150. displayMessage("\n" + "Incorrect!");
  151.  
  152. }
  153.  
  154. //displayMessage("\n" + serverAnswer);
  155.  
  156. }
  157. catch (ScriptException e) {
  158. // Something went wrong
  159. e.printStackTrace();
  160. }
  161. catch (ClassNotFoundException classNotFoundException){
  162. displayMessage ( "\nUnknown object type received" );
  163. }
  164.  
  165.  
  166. displayMessage( "\n" + message ); // display message
  167. } // end try
  168. /* catch ( ClassNotFoundException classNotFoundException )
  169.   {
  170.   displayMessage( "\nUnknown object type received" );
  171.   } // end catch
  172.  
  173.   } */while ( !message.equals( "CLIENT>>> TERMINATE" ) );
  174.  
  175.  
  176. } // end method processConnection
  177.  
  178.  
  179. // close streams and socket
  180. private void closeConnection()
  181. {
  182. displayMessage( "\nTerminating connection\n" );
  183. setTextFieldEditable( false ); // disable enterField
  184.  
  185. try
  186. {
  187. output.close(); // close output stream
  188. input.close(); // close input stream
  189. connection.close(); // close socket
  190. } // end try
  191. catch ( IOException ioException )
  192. {
  193. ioException.printStackTrace();
  194. } // end catch
  195. } // end method closeConnection
  196.  
  197. // send message to client
  198. private void sendData( String message )
  199. {
  200. try // send object to client
  201. {
  202. output.writeObject( "SERVER>>> " + message );
  203. output.flush(); // flush output to client
  204. displayMessage( "\nSERVER>>> " + message );
  205. } // end try
  206. catch ( IOException ioException )
  207. {
  208. displayArea.append( "\nError writing object" );
  209. } // end catch
  210. } // end method sendData
  211.  
  212. // manipulates displayArea in the event-dispatch thread
  213. private void displayMessage( final String messageToDisplay )
  214. {
  215. SwingUtilities.invokeLater(
  216. new Runnable()
  217. {
  218. public void run() // updates displayArea
  219. {
  220. displayArea.append( messageToDisplay ); // append message
  221. } // end method run
  222. } // end anonymous inner class
  223. ); // end call to SwingUtilities.invokeLater
  224. } // end method displayMessage
  225.  
  226. // manipulates enterField in the event-dispatch thread
  227. private void setTextFieldEditable( final boolean editable )
  228. {
  229. SwingUtilities.invokeLater(
  230. new Runnable()
  231. {
  232. public void run() // sets enterField's editability
  233. {
  234. enterField.setEditable( editable );
  235. } // end method run
  236. } // end inner class
  237. ); // end call to SwingUtilities.invokeLater
  238. } // end method setTextFieldEditable
  239. } // end class Server

  1. import javax.swing.JFrame;
  2.  
  3. public class ServerTest
  4. {
  5. public static void main( String args[] )
  6. {
  7. Server application = new Server(); // create server
  8. application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
  9. application.runServer(); // run server application
  10. } // end main
  11. } // end class ServerTest

  1. import java.io.EOFException;
  2. import java.io.IOException;
  3. import java.io.ObjectInputStream;
  4. import java.io.ObjectOutputStream;
  5. import java.net.InetAddress;
  6. import java.net.Socket;
  7. import java.awt.BorderLayout;
  8. import java.awt.event.ActionEvent;
  9. import java.awt.event.ActionListener;
  10. import javax.swing.JFrame;
  11. import javax.swing.JScrollPane;
  12. import javax.swing.JTextArea;
  13. import javax.swing.JTextField;
  14. import javax.swing.SwingUtilities;
  15. import javax.swing.JLabel;
  16.  
  17. public class Client extends JFrame
  18. {
  19. private JTextField equationField; // enter equation here
  20. private JTextField answerField;//enter answer here
  21. private JTextArea displayArea; // display information to user
  22. private ObjectOutputStream output; // output stream to server
  23. private ObjectInputStream input; // input stream from server
  24. private String message = ""; // message from server
  25. private String chatServer; // host server for this application
  26. private Socket client; // socket to communicate with server
  27. private JLabel label;//direction label
  28.  
  29. // initialize chatServer and set up GUI
  30. public Client( String host )
  31. {
  32. super( "Client" );
  33.  
  34. chatServer = host; // set server to which this client connects
  35. /*
  36.   label = new JLabel("Enter equation above and answer below.");//create label
  37.   add (label, BorderLayout.NORTH);
  38.   */
  39. equationField = new JTextField(); // create enterField
  40. equationField.setEditable( false );
  41. equationField.addActionListener(
  42. new ActionListener()
  43. {
  44. // send message to server
  45. public void actionPerformed( ActionEvent event )
  46. {
  47. sendData( event.getActionCommand() );
  48. equationField.setText( "" );
  49. } // end method actionPerformed
  50. } // end anonymous inner class
  51. ); // end call to addActionListener
  52.  
  53. add( equationField, BorderLayout.NORTH);
  54.  
  55. answerField = new JTextField(); // create enterField
  56. answerField.setEditable( false );
  57. answerField.addActionListener(
  58. new ActionListener()
  59. {
  60. // send message to server
  61. public void actionPerformed( ActionEvent event )
  62. {
  63. sendData( event.getActionCommand() );
  64. answerField.setText( "" );
  65. } // end method actionPerformed
  66. } // end anonymous inner class
  67. ); // end call to addActionListener
  68.  
  69. add( answerField, BorderLayout.SOUTH );
  70.  
  71. displayArea = new JTextArea(); // create displayArea
  72. add( new JScrollPane( displayArea ), BorderLayout.CENTER);
  73.  
  74. setSize( 500, 250 ); // set size of window
  75. setVisible( true ); // show window
  76. } // end Client constructor
  77.  
  78. // connect to server and process messages from server
  79. public void runClient()
  80. {
  81. try // connect to server, get streams, process connection
  82. {
  83. connectToServer(); // create a Socket to make connection
  84. getStreams(); // get the input and output streams
  85. processConnection(); // process connection
  86. } // end try
  87. catch ( EOFException eofException )
  88. {
  89. displayMessage( "\nClient terminated connection" );
  90. } // end catch
  91. catch ( IOException ioException )
  92. {
  93. ioException.printStackTrace();
  94. } // end catch
  95. finally
  96. {
  97. closeConnection(); // close connection
  98. } // end finally
  99. } // end method runClient
  100.  
  101. // connect to server
  102. private void connectToServer() throws IOException
  103. {
  104. displayMessage( "Attempting connection\n" );
  105.  
  106. // create Socket to make connection to server
  107. client = new Socket( InetAddress.getByName( chatServer ), 12345 );
  108. displayMessage("Enter equation in top field and answer in the bottom field\n");
  109. // display connection information
  110. displayMessage( "Connected to: " +
  111. client.getInetAddress().getHostName() );
  112.  
  113. } // end method connectToServer
  114.  
  115. // get streams to send and receive data
  116. private void getStreams() throws IOException
  117. {
  118. // set up output stream for objects
  119. output = new ObjectOutputStream( client.getOutputStream() );
  120. output.flush(); // flush output buffer to send header information
  121.  
  122. // set up input stream for objects
  123. input = new ObjectInputStream( client.getInputStream() );
  124.  
  125. displayMessage( "\nGot I/O streams\n" );
  126. } // end method getStreams
  127.  
  128. // process connection with server
  129. private void processConnection() throws IOException
  130. {
  131. // enable enterField so client user can send messages
  132. setTextFieldEditable( true );
  133.  
  134. do // process messages sent from server
  135. {
  136. try // read message and display it
  137. {
  138. message = ( String ) input.readObject(); // read new message
  139. displayMessage( "\n" + message ); // display message
  140. } // end try
  141. catch ( ClassNotFoundException classNotFoundException )
  142. {
  143. displayMessage( "\nUnknown object type received" );
  144. } // end catch
  145.  
  146. } while ( !message.equals( "SERVER>>> TERMINATE" ) );
  147. } // end method processConnection
  148.  
  149. // close streams and socket
  150. private void closeConnection()
  151. {
  152. displayMessage( "\nClosing connection" );
  153. setTextFieldEditable( false ); // disable enterField
  154.  
  155. try
  156. {
  157. output.close(); // close output stream
  158. input.close(); // close input stream
  159. client.close(); // close socket
  160. } // end try
  161. catch ( IOException ioException )
  162. {
  163. ioException.printStackTrace();
  164. } // end catch
  165. } // end method closeConnection
  166.  
  167. // send message to server
  168. private void sendData( String message )
  169. {
  170. try // send object to server
  171. {
  172. output.writeObject( "CLIENT>>> " + message );
  173. output.flush(); // flush data to output
  174. displayMessage( "\nCLIENT>>> " + message );
  175. } // end try
  176. catch ( IOException ioException )
  177. {
  178. displayArea.append( "\nError writing object" );
  179. } // end catch
  180. } // end method sendData
  181.  
  182. // manipulates displayArea in the event-dispatch thread
  183. private void displayMessage( final String messageToDisplay )
  184. {
  185. SwingUtilities.invokeLater(
  186. new Runnable()
  187. {
  188. public void run() // updates displayArea
  189. {
  190. displayArea.append( messageToDisplay );
  191. } // end method run
  192. } // end anonymous inner class
  193. ); // end call to SwingUtilities.invokeLater
  194. } // end method displayMessage
  195.  
  196. // manipulates enterField in the event-dispatch thread
  197. private void setTextFieldEditable( final boolean editable )
  198. {
  199. SwingUtilities.invokeLater(
  200. new Runnable()
  201. {
  202. public void run() // sets enterField's editability
  203. {
  204. equationField.setEditable( editable );
  205. answerField.setEditable(editable);
  206. } // end method run
  207. } // end anonymous inner class
  208. ); // end call to SwingUtilities.invokeLater
  209. } // end method setTextFieldEditable
  210. } // end class Client

  1. import javax.swing.JFrame;
  2.  
  3. public class ClientTest
  4. {
  5. public static void main( String args[] )
  6. {
  7. Client application; // declare client application
  8.  
  9. // if no command line args
  10. if ( args.length == 0 )
  11. application = new Client( "127.0.0.1" ); // connect to localhost
  12. else
  13. application = new Client( args[ 0 ] ); // use args to connect
  14.  
  15. application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
  16. application.runClient(); // run client application
  17. } // end main
  18. } // end class ClientTest
Reply With Quote Quick reply to this message  
Join Date: Nov 2008
Posts: 332
Reputation: quuba is on a distinguished road 
Solved Threads: 54
quuba quuba is offline Offline
Posting Whiz

Re: Unable to populate String.

 
1
  #2
Jan 23rd, 2009
  1. private void processConnection() throws IOException {
  2. String message = "Connection successful";
  3. ...
  4. message = (String) input.readObject(); // read new message
  5. displayMessage("\n|" + message + "|");
  6. ///"CLIENT>>> " TO REMOVE!
  7. message = message.substring(10);
  8. ...
it's all
Reply With Quote Quick reply to this message  
Join Date: Aug 2008
Posts: 13
Reputation: AllenB is an unknown quantity at this point 
Solved Threads: 0
AllenB AllenB is offline Offline
Newbie Poster

Re: Unable to populate String.

 
0
  #3
Jan 23rd, 2009
Thank you! That's all I needed.
Reply With Quote Quick reply to this message  
Reply

This thread has been marked solved.
Perhaps start a new thread instead?
Message:


Thread Tools Search this Thread



Tag cloud for Java
About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC