472,145 Members | 1,492 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,145 software developers and data experts.

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:
Expand|Select|Wrap|Line Numbers
  1. import java.io.*;
  2. import java.net.*;
  3.  
  4.  
  5. public class serverForm extends javax.swing.JFrame {
  6.  
  7.    private PrintWriter output = null; 
  8.    private BufferedReader input = null; 
  9.    private ServerSocket server = null; 
  10.    private Socket connection = null; 
  11.  
  12.     public serverForm() {
  13.         initComponents();
  14.     }
  15.  
  16.  
  17.     public void runServer()
  18.    {
  19.             try 
  20.       {
  21.          server = new ServerSocket( Integer.parseInt(jTextField1.getText()), 2 ); 
  22.  
  23.  
  24. } catch (IOException e) {
  25.             System.err.println("Could not listen on port: 4444.");
  26.             System.exit(1);
  27.         }
  28.  
  29.             try 
  30.             {
  31.               waitForConnection();      
  32.  
  33.             } 
  34.  
  35.             catch ( IOException ioException ) 
  36.      {
  37.         ioException.printStackTrace();
  38.      }
  39.  
  40.             try 
  41.             {
  42.               output = new PrintWriter(connection.getOutputStream(), true);
  43.               input = new BufferedReader(new InputStreamReader(connection.getInputStream()));  
  44.               processConnection();
  45.             } 
  46.  
  47.             catch ( IOException ioException ) 
  48.      {
  49.         ioException.printStackTrace();
  50.      }
  51.             finally 
  52.             {
  53.                closeConnection(); 
  54.  
  55.             }
  56.  
  57. }
  58.  
  59.    private void waitForConnection() throws IOException
  60.    {
  61.      statuslbl.setText( "Waiting for connection\n" );
  62.       connection = server.accept();          
  63.       statuslbl.setText( "Connection received from: " + connection.getInetAddress().getHostName() );
  64.    } 
  65.  
  66.  
  67.  
  68.       private void processConnection() throws IOException
  69.    {
  70.      String inputLine, outputLine;
  71.        protocol kkp = new protocol();
  72.  
  73.         outputLine = kkp.processInput(null);
  74.         output.println(outputLine);
  75.  
  76.         jTextArea1.setText(jTextArea1.getText() + outputLine + "\n");
  77.         while ((inputLine = input.readLine()) != null)
  78.         {
  79.              outputLine = kkp.processInput(inputLine);
  80.  
  81.              jTextArea1.setText(jTextArea1.getText() + inputLine + "\n");
  82.                 jTextArea1.setText(jTextArea1.getText() + outputLine + "\n");
  83.       try 
  84.       {
  85.          output.println(outputLine);
  86.       } 
  87.       catch ( Exception e) 
  88.       {
  89.      statuslbl.setText( "Error writing object" );
  90.       } 
  91.  
  92.  
  93.              if (outputLine.equals("Bye."))
  94.                 break;
  95.         }
  96.  
  97.  
  98.  
  99.  
  100.       }
  101.  
  102.       private void closeConnection() 
  103.    {
  104.       statuslbl.setText( "Terminating connection" );
  105.  
  106.       try 
  107.       {
  108.  
  109.          output.close();
  110.          input.close();
  111.          connection.close();
  112.       } 
  113.       catch ( IOException ioException ) 
  114.       {
  115.          ioException.printStackTrace();
  116.       } 
  117.    } 
  118.  
  119.  
  120.  
  121.        private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
  122.        runServer();
  123.     }                                        
  124.  
  125.     /**
  126.      * @param args the command line arguments
  127.      */
  128.     public static void main(String args[]) {
  129.         java.awt.EventQueue.invokeLater(new Runnable() {
  130.             public void run() {
  131.                 new serverForm().setVisible(true);
  132.             }
  133.         });
  134.  
  135.     }
Here is protocol class which the server works from:
Expand|Select|Wrap|Line Numbers
  1. import java.net.*;
  2. import java.io.*;
  3.  
  4. public class protocol {
  5.     private static final int WAITING = 0;
  6.     private static final int SENTKNOCKKNOCK = 1;
  7.     private static final int SENTCLUE = 2;
  8.     private static final int ANOTHER = 3;
  9.  
  10.     private static final int NUMJOKES = 5;
  11.  
  12.     private int state = WAITING;
  13.     private int currentJoke = 0;
  14.  
  15.     private String[] clues = { "Turnip", "Little Old Lady", "Atch", "Who", "Who" };
  16.     private String[] answers = { "Turnip the heat, it's cold in here!",
  17.                                  "I didn't know you could yodel!",
  18.                                  "Bless you!",
  19.                                  "Is there an owl in here?",
  20.                                  "Is there an echo in here?" };
  21.  
  22.     public String processInput(String theInput) {
  23.         String theOutput = null;
  24.  
  25.         if (state == WAITING) {
  26.             theOutput = "Knock! Knock!";
  27.             state = SENTKNOCKKNOCK;
  28.         } else if (state == SENTKNOCKKNOCK) {
  29.             if (theInput.equalsIgnoreCase("Who's there?")) {
  30.                 theOutput = clues[currentJoke];
  31.                 state = SENTCLUE;
  32.             } else {
  33.                 theOutput = "You're supposed to say \"Who's there?\"! " +
  34.                 "Try again. Knock! Knock!";
  35.             }
  36.         } else if (state == SENTCLUE) {
  37.             if (theInput.equalsIgnoreCase(clues[currentJoke] + " who?")) {
  38.                 theOutput = answers[currentJoke] + " Want another? (y/n)";
  39.                 state = ANOTHER;
  40.             } else {
  41.                 theOutput = "You're supposed to say \"" + 
  42.                 clues[currentJoke] + 
  43.                 " who?\"" + 
  44.                 "! Try again. Knock! Knock!";
  45.                 state = SENTKNOCKKNOCK;
  46.             }
  47.         } else if (state == ANOTHER) {
  48.             if (theInput.equalsIgnoreCase("y")) {
  49.                 theOutput = "Knock! Knock!";
  50.                 if (currentJoke == (NUMJOKES - 1))
  51.                     currentJoke = 0;
  52.                 else
  53.                     currentJoke++;
  54.                 state = SENTKNOCKKNOCK;
  55.             } else {
  56.                 theOutput = "Bye.";
  57.                 state = WAITING;
  58.             }
  59.         }
  60.         return theOutput;
  61.     }
  62. }
And here is the client code:
Expand|Select|Wrap|Line Numbers
  1. import java.io.*;
  2. import java.net.*;
  3.  
  4. public class ClientForm extends javax.swing.JFrame {
  5.    private Socket kkSocket = new Socket();
  6.    private PrintWriter out = null;
  7.    private BufferedReader in = null;
  8.     /** Creates new form NewJFrame */
  9.     public ClientForm() {
  10.         initComponents();
  11.        }
  12.  
  13.     public void send()
  14.     {
  15.      if (kkSocket.isConnected() != true)
  16.             statuslbl.setText("Please Connect First");
  17.    else
  18.        try
  19.        {
  20.            String client,server;
  21.  
  22.             client = clientInput.getText();               
  23.             out.println(client);
  24.             server = (String)in.readLine();
  25.  
  26.  
  27.                 if (server.equals("Bye."))
  28.                 {
  29.                     in.close();
  30.                     out.close();
  31.                     kkSocket.close();
  32.                 }
  33.  
  34.             jTextArea1.setText(jTextArea1.getText() + "User : " + client + "\n");
  35.             jTextArea1.setText(jTextArea1.getText() + "Server : " + server + "\n");   
  36.             }
  37.             catch (IOException e)
  38.             {
  39.             }
  40.  
  41.  
  42.             clientInput.setText("");
  43.  
  44.  
  45.  
  46.     }
  47.   private void connectbtnActionPerformed(java.awt.event.ActionEvent evt) {                                           
  48.  
  49.          try 
  50.         {
  51.          if (kkSocket.isConnected() == true)  
  52.              kkSocket.close();
  53.  
  54.        kkSocket = new Socket(ipText.getText(),Integer.parseInt(portText.getText()));
  55.  
  56.  
  57.  
  58.         out = new PrintWriter(kkSocket.getOutputStream(), true);
  59.         in = new BufferedReader(new InputStreamReader( kkSocket.getInputStream()));
  60.  
  61.         jTextArea1.setText(jTextArea1.getText() + "Server : " + (String)in.readLine() + "\n");
  62.         } 
  63.           catch (Exception e) 
  64.           {
  65.             statuslbl.setText("Can't Connect To Host");
  66.           } 
  67.  
  68.         if (kkSocket.isConnected() == true)
  69.              statuslbl.setText("Connected");
  70. }                                          
  71.  
  72.     private void clientInputActionPerformed(java.awt.event.ActionEvent evt) {                                            
  73.       send();
  74.     }                                           
  75.  
  76.     private void sendbtnActionPerformed(java.awt.event.ActionEvent evt) {                                        
  77.  send();
  78.  
  79.  
  80. }                                       
  81.  
  82.  
  83.  
  84.     /**
  85.      * @param args the command line arguments
  86.      */
  87.     public static void main(String args[]) {
  88.         java.awt.EventQueue.invokeLater(new Runnable() {
  89.             public void run() {
  90.                 new ClientForm().setVisible(true);
  91.             }
  92.         });
  93.  
  94.     }
Jul 30 '09 #1
10 3871
JosAH
11,448 Expert 8TB
@Elaine121
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
Jul 30 '09 #2
i'm not that familiar with threads. What's the best way to do that?
Jul 30 '09 #3
JosAH
11,448 Expert 8TB
@Elaine121
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
Jul 30 '09 #4
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
Jul 30 '09 #5
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.

Expand|Select|Wrap|Line Numbers
  1. public static void main(String args[]) {
  2.         //java.awt.EventQueue.invokeLater(new Runnable() {
  3.  
  4.                  SwingUtilities.invokeLater(new Runnable() {
  5.                  public void run() {
  6.                 new serverForm().setVisible(true);
  7.                 Thread newThread = new Thread(new serverForm());
  8.                 newThread.start();
  9.             }
  10.         });
}
Jul 30 '09 #6
JosAH
11,448 Expert 8TB
@Elaine121
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
Jul 30 '09 #7
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.

Expand|Select|Wrap|Line Numbers
  1. server = new ServerSocket( Integer.parseInt(jTextField1.getText())); // this gives exception
  2. server = new ServerSocket( 63100); // this runs fine
Am i reading the number wrong?
Jul 30 '09 #8
JosAH
11,448 Expert 8TB
@Elaine121
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
Jul 30 '09 #9
So then where must i put that code? i tried a couple of places but its still the same
Jul 30 '09 #10
JosAH
11,448 Expert 8TB
@Elaine121
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
Jul 30 '09 #11

Post your reply

Sign in to post your reply or Sign up for a free account.

Similar topics

4 posts views Thread by Lorenzo | last post: by
5 posts views Thread by Rowland | last post: by
2 posts views Thread by Krzysztof Paz | last post: by
oll3i
reply views Thread by oll3i | last post: by
reply views Thread by Saiars | last post: by
reply views Thread by leo001 | last post: by

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.