473,396 Members | 2,151 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 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 4189
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

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

Similar topics

4
by: Lorenzo | last post by:
hi you all, first of all apologies for having cross-posted this message but really i did not know where to post it. please let me know what ng you consider the most suitable for the described...
5
by: Rowland | last post by:
Hi, I know this question has prob. been asked a million times, but I couldn't find it in the FAQ, so here goes : I'm trying to write a Java applet to call a dll that resides on the web server...
1
by: Krzysztof Pa¼ | last post by:
Hi, I want to make simple client in phyton, which would be able to communicate with Java server using SSL sockets. There is the Java clients, which is doing this - so I'm pretty sure, that Java...
2
by: Krzysztof Paz | last post by:
Hi, There is a Java (SUN 1.4) server which using Object Input/Output Streams at SSL/Socket to communicate with Java clients. Now there is a request for making C# Client for this server also. SSL...
4
by: yaron | last post by:
Hi, I have a problem when sending data over TCP socket from c# client to java server. the connection established ok, but i can't send data from c# client to java server. it's work ok with...
2
by: Jobs | last post by:
Download the JAVA , .NET and SQL Server interview with answers Download the JAVA , .NET and SQL Server interview sheet and rate yourself. This will help you judge yourself are you really worth of...
0
oll3i
by: oll3i | last post by:
package library.common; import java.sql.ResultSet; public interface LibraryInterface { public ResultSet getBookByAuthor(String author); public ResultSet getBookByName(String name);
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

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.