473,757 Members | 9,145 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 #1
10 4251
JosAH
11,448 Recognized Expert MVP
@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
Elaine121
23 New Member
i'm not that familiar with threads. What's the best way to do that?
Jul 30 '09 #3
JosAH
11,448 Recognized Expert MVP
@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
Elaine121
23 New Member
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
Elaine121
23 New Member
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 Recognized Expert MVP
@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
Elaine121
23 New Member
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 Recognized Expert MVP
@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
Elaine121
23 New Member
So then where must i put that code? i tried a couple of places but its still the same
Jul 30 '09 #10

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
5431
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
8775
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
8200
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
6964
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
9489
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
9298
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
9885
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
9737
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7286
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
6562
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();...
1
3829
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
3399
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2698
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.