473,550 Members | 2,881 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 4208
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
5420
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...
5
13638
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...
1
5424
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...
2
8763
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...
4
8193
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
6934
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
3243
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
7560
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...
0
7487
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...
0
7758
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
7998
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...
1
7517
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...
0
6098
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...
0
5126
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...
0
3530
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
1
1978
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

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.