473,769 Members | 2,081 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Java client server connection problem

23 New Member
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
10 4255
JosAH
11,448 Recognized Expert MVP
@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
5428
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 issue. i wrote a program made by a client and a server that communicate via RMI premise 1) everything has been developed and executed on WinXP Professional and the following jre
5
13647
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 (running IIS 6). I've written a little test applet that should call a helloWorld function in the dll, but when I use System.loadLibrary, it gives me this security warning :
1
5434
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 server works OK. I've heard, that P2.3 has SSL support included in himself and also, I was trying P2.2 with pyOpenSSL wrappers and extensions, but unsuccesfuly... So, could you give me a few lines of python code which makes such things:
2
8778
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 layer could be done with Org.Mentalis.Security.dll from seclib-1.0 Mentalis package - its fine... But, threre is a problem: How to properly communicate from C# language to Java.ObjectInputStream - cause I've tried many times, and always get the...
4
8202
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 TcpClient, NetworkStream and StreamWriter classes. but with low level socket it doesn't work (When using the Socket class Send method).
2
6966
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 attending interviews. If you own a company best way to judge if the candidate is worth of it. http://www.questpond.com/InterviewRatingSheet.zip
0
3286
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
9589
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10049
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9997
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8873
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7413
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6675
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5448
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3565
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2815
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.