Java client server connection problem

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Elaine121
    New Member
    • Aug 2007
    • 23

    Java client server connection problem

    Hi i've been batteling for hours and can't seem to find the problem. When my server runs and I press the connect button the gui freezes until the client gui is terminated.. only then the gui becomes active again and displays the messages.

    Here is my server code:
    Code:
    import java.io.*;
    import java.net.*;
    
    
    public class serverForm extends javax.swing.JFrame {
        
       private PrintWriter output = null; 
       private BufferedReader input = null; 
       private ServerSocket server = null; 
       private Socket connection = null; 
     
        public serverForm() {
            initComponents();
        }
        
        
        public void runServer()
       {
                try 
          {
             server = new ServerSocket( Integer.parseInt(jTextField1.getText()), 2 ); 
             
           
    } catch (IOException e) {
                System.err.println("Could not listen on port: 4444.");
                System.exit(1);
            }
    
                try 
                {
                  waitForConnection();      
                  
                } 
                
                catch ( IOException ioException ) 
         {
            ioException.printStackTrace();
         }
                
                try 
                {
                  output = new PrintWriter(connection.getOutputStream(), true);
                  input = new BufferedReader(new InputStreamReader(connection.getInputStream()));  
                  processConnection();
                } 
               
                catch ( IOException ioException ) 
         {
            ioException.printStackTrace();
         }
                finally 
                {
                   closeConnection(); 
                 
                }
          
    }
            
       private void waitForConnection() throws IOException
       {
         statuslbl.setText( "Waiting for connection\n" );
          connection = server.accept();          
          statuslbl.setText( "Connection received from: " + connection.getInetAddress().getHostName() );
       } 
           
        
        
          private void processConnection() throws IOException
       {
         String inputLine, outputLine;
           protocol kkp = new protocol();
    
            outputLine = kkp.processInput(null);
            output.println(outputLine);
            
            jTextArea1.setText(jTextArea1.getText() + outputLine + "\n");
            while ((inputLine = input.readLine()) != null)
            {
                 outputLine = kkp.processInput(inputLine);
                
                 jTextArea1.setText(jTextArea1.getText() + inputLine + "\n");
                    jTextArea1.setText(jTextArea1.getText() + outputLine + "\n");
          try 
          {
             output.println(outputLine);
          } 
          catch ( Exception e) 
          {
         statuslbl.setText( "Error writing object" );
          } 
                 
                 
                 if (outputLine.equals("Bye."))
                    break;
            }
            
    
    
    
          }
          
          private void closeConnection() 
       {
          statuslbl.setText( "Terminating connection" );
    
          try 
          {
               
             output.close();
             input.close();
             connection.close();
          } 
          catch ( IOException ioException ) 
          {
             ioException.printStackTrace();
          } 
       } 
          
    
    
           private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
           runServer();
        }                                        
        
        /**
         * @param args the command line arguments
         */
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new serverForm().setVisible(true);
                }
            });
            
        }
    Here is protocol class which the server works from:
    Code:
    import java.net.*;
    import java.io.*;
    
    public class protocol {
        private static final int WAITING = 0;
        private static final int SENTKNOCKKNOCK = 1;
        private static final int SENTCLUE = 2;
        private static final int ANOTHER = 3;
    
        private static final int NUMJOKES = 5;
    
        private int state = WAITING;
        private int currentJoke = 0;
    
        private String[] clues = { "Turnip", "Little Old Lady", "Atch", "Who", "Who" };
        private String[] answers = { "Turnip the heat, it's cold in here!",
                                     "I didn't know you could yodel!",
                                     "Bless you!",
                                     "Is there an owl in here?",
                                     "Is there an echo in here?" };
    
        public String processInput(String theInput) {
            String theOutput = null;
    
            if (state == WAITING) {
                theOutput = "Knock! Knock!";
                state = SENTKNOCKKNOCK;
            } else if (state == SENTKNOCKKNOCK) {
                if (theInput.equalsIgnoreCase("Who's there?")) {
                    theOutput = clues[currentJoke];
                    state = SENTCLUE;
                } else {
                    theOutput = "You're supposed to say \"Who's there?\"! " +
    			    "Try again. Knock! Knock!";
                }
            } else if (state == SENTCLUE) {
                if (theInput.equalsIgnoreCase(clues[currentJoke] + " who?")) {
                    theOutput = answers[currentJoke] + " Want another? (y/n)";
                    state = ANOTHER;
                } else {
                    theOutput = "You're supposed to say \"" + 
    			    clues[currentJoke] + 
    			    " who?\"" + 
    			    "! Try again. Knock! Knock!";
                    state = SENTKNOCKKNOCK;
                }
            } else if (state == ANOTHER) {
                if (theInput.equalsIgnoreCase("y")) {
                    theOutput = "Knock! Knock!";
                    if (currentJoke == (NUMJOKES - 1))
                        currentJoke = 0;
                    else
                        currentJoke++;
                    state = SENTKNOCKKNOCK;
                } else {
                    theOutput = "Bye.";
                    state = WAITING;
                }
            }
            return theOutput;
        }
    }
    And here is the client code:
    Code:
    import java.io.*;
    import java.net.*;
    
    public class ClientForm extends javax.swing.JFrame {
       private Socket kkSocket = new Socket();
       private PrintWriter out = null;
       private BufferedReader in = null;
        /** Creates new form NewJFrame */
        public ClientForm() {
            initComponents();
           }
        
        public void send()
        {
         if (kkSocket.isConnected() != true)
                statuslbl.setText("Please Connect First");
       else
           try
           {
               String client,server;
                
                client = clientInput.getText();               
                out.println(client);
                server = (String)in.readLine();
                
                
                    if (server.equals("Bye."))
                    {
                        in.close();
                        out.close();
                        kkSocket.close();
                    }
                    
                jTextArea1.setText(jTextArea1.getText() + "User : " + client + "\n");
                jTextArea1.setText(jTextArea1.getText() + "Server : " + server + "\n");   
                }
                catch (IOException e)
                {
                }
                
                
                clientInput.setText("");
                
            
           
        }
      private void connectbtnActionPerformed(java.awt.event.ActionEvent evt) {                                           
           
             try 
            {
             if (kkSocket.isConnected() == true)  
                 kkSocket.close();
                
           kkSocket = new Socket(ipText.getText(),Integer.parseInt(portText.getText()));
           
            
            
            out = new PrintWriter(kkSocket.getOutputStream(), true);
            in = new BufferedReader(new InputStreamReader( kkSocket.getInputStream()));
            
            jTextArea1.setText(jTextArea1.getText() + "Server : " + (String)in.readLine() + "\n");
            } 
              catch (Exception e) 
              {
                statuslbl.setText("Can't Connect To Host");
              } 
            
            if (kkSocket.isConnected() == true)
                 statuslbl.setText("Connected");
    }                                          
    
        private void clientInputActionPerformed(java.awt.event.ActionEvent evt) {                                            
          send();
        }                                           
    
        private void sendbtnActionPerformed(java.awt.event.ActionEvent evt) {                                        
     send();
            
           
    }                                       
       
           
        
        /**
         * @param args the command line arguments
         */
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new ClientForm().setVisible(true);
                }
            });
       
        }
  • JosAH
    Recognized Expert MVP
    • Mar 2007
    • 11453

    #2
    Originally posted by Elaine121
    Hi i've been batteling for hours and can't seem to find the problem. When my server runs and I press the connect button the gui freezes until the client gui is terminated.. only then the gui becomes active again and displays the messages.
    I didn't read all your code but given your description I conclude that you do all your processing in the EDT thread (Event Dispatch Thread). You are keeping that thread busy with your accept() and read() calls; they are blocking methods, i.e. they don't return until they have done their job. The EDT doesn't have any time anymore to do its job: painting components and listening for events.

    Do all of your processing in another thread so the EDT can do its job while you do your job.

    kind regards,

    Jos

    Comment

    • Elaine121
      New Member
      • Aug 2007
      • 23

      #3
      i'm not that familiar with threads. What's the best way to do that?

      Comment

      • JosAH
        Recognized Expert MVP
        • Mar 2007
        • 11453

        #4
        Originally posted by Elaine121
        i'm not that familiar with threads. What's the best way to do that?
        Create an implementation of the Runnable interface that handles all the socket communication; feed it to a new Thread and start the thread. That''s basically it.

        kind regards,

        Jos

        Comment

        • Elaine121
          New Member
          • Aug 2007
          • 23

          #5
          That sounds easy to do and I tried looking it up and I'm sorry but I have no idea what to do. Im new at this so everything is a bit complicated for me

          Comment

          • Elaine121
            New Member
            • Aug 2007
            • 23

            #6
            ok I don't know if I'm on the right track with this.. in my server class I created a new thread. But now when i run the server class and press the connect button it just gives me an IOexception.

            Code:
            public static void main(String args[]) {
                    //java.awt.EventQueue.invokeLater(new Runnable() {
                     
                             SwingUtilities.invokeLater(new Runnable() {
                             public void run() {
                            new serverForm().setVisible(true);
                            Thread newThread = new Thread(new serverForm());
                            newThread.start();
                        }
                    });
            }

            Comment

            • JosAH
              Recognized Expert MVP
              • Mar 2007
              • 11453

              #7
              Originally posted by Elaine121
              ok I don't know if I'm on the right track with this.. in my server class I created a new thread. But now when i run the server class and press the connect button it just gives me an IOexception.
              Of course the Exception stack trace told you exactly where the exception happened; reading such stack traces actually helps you finding the bug ...

              kind regards,

              Jos

              Comment

              • Elaine121
                New Member
                • Aug 2007
                • 23

                #8
                when the port number is already in the textbox then the server runs fine.. but when i enter a number myself thats when the exception occurs.

                Code:
                server = new ServerSocket( Integer.parseInt(jTextField1.getText())); // this gives exception
                server = new ServerSocket( 63100); // this runs fine
                Am i reading the number wrong?

                Comment

                • JosAH
                  Recognized Expert MVP
                  • Mar 2007
                  • 11453

                  #9
                  Originally posted by Elaine121
                  when the port number is already in the textbox then the server runs fine.. but when i enter a number myself thats when the exception occurs.

                  Code:
                  server = new ServerSocket( Integer.parseInt(jTextField1.getText())); // this gives exception
                  server = new ServerSocket( 63100); // this runs fine
                  Am i reading the number wrong?
                  If that code runs before you could enter a number in the text field there won't be a number yet and the parseInt() method will throw another Exception. Otherwise (if the field contains a valid number) all will be fine.

                  kind regards,

                  Jos

                  Comment

                  • Elaine121
                    New Member
                    • Aug 2007
                    • 23

                    #10
                    So then where must i put that code? i tried a couple of places but its still the same

                    Comment

                    • JosAH
                      Recognized Expert MVP
                      • Mar 2007
                      • 11453

                      #11
                      Originally posted by Elaine121
                      So then where must i put that code? i tried a couple of places but its still the same
                      You should only run that piece of code when the user has completed typing a number in that field. An event handler would do fine. It should start a thread that opens up a server and starts communicating with clients while the EDT goes on painting and listening for other events.

                      kind regards,

                      Jos

                      Comment

                      Working...