Results 1 to 6 of 6
Like Tree1Likes
  • 1 Post By jim829

Thread: TCP connection in the background thread. How to handle JDialogs?

  1. #1
    igorland is offline Member
    Join Date
    Jan 2013
    Posts
    86
    Rep Power
    0

    Default TCP connection in the background thread. How to handle JDialogs?

    I am trying to send a message to server via TCP/IP, wait for the response, and perform further actions dependent on the response. While the communication is in the background process, a JDialog with spinning activity indicator should be displayed. Furthermore, if there is an error in the connection, another JDialog should be displayed.

    This is the method that invokes the connection as a result of pressing a button:

    Java Code:
     public void sendMessage()
        {
           JFrame f = new JFrame(); 
           JDialog modalDialog = new JDialog(f, "Busy", Dialog.ModalityType.MODELESS);
           modalDialog.setSize(200, 100);
           modalDialog.setLocationRelativeTo(f);
           modalDialog.setUndecorated(true);
           // Remove menu buttons
           modalDialog.getRootPane().setWindowDecorationStyle(JRootPane.NONE);
           modalDialog.getContentPane().setBackground( Color.WHITE );
           // Add rotating activity indicator
           ImageIcon loading = new ImageIcon("src/images/activityIndicator.gif");
           modalDialog.add(new JLabel("Please wait... ", loading, JLabel.CENTER));
           // Set activity indicator visible
           modalDialog.setVisible(true);
            
            // Create connection object
            IGAConnectionTCP t = new IGAConnectionTCP(makeMessageToServerFlightplan());
            
            // Start connection
            t.start();
                
            synchronized(t)
            {
                /* Create notification dialog */         
                try
                {
                    t.wait();
                }
                catch(InterruptedException e)
                {
                    
                }
                    
                    
                /*  When the activity in the background thread ends, change GUI on the
                    dispatch thread. */
                SwingUtilities.invokeLater(() ->
                { 
                    t.closeConnection();
                    
                    // Close the pop-up menu when finished
                    modalDialog.setVisible(false);
                    modalDialog.dispose();
    
                }); 
            }
        }
    This is the TCP Connection class:

    Java Code:
    public class IGAConnectionTCP extends Thread
    {
          /** Object to AppSingleton */
          AppSingleton appSingleton = AppSingleton.getInstance( );
          /** Terminator: Message from the server that ends the connection. */
          private final String  terminator = "END_IGOCONNECT_DATA";
          /** Message that will be sent to the server. */
          private String messageToServer;
          /** Instance of Socket. */
          Socket socket;
          /** Instance of DataInputStream. */    
          DataInputStream input;
          /** Instance of DataOutputStream. */  
          DataOutputStream output;
          /** Instance of BufferedReader. */  
          BufferedReader br;
          /** Message that will be sent from the server. */
          private String messageFromServer;
            
          public IGAConnectionTCP(String messageToServer)
          {
            this.messageToServer = messageToServer;
          }
            
    
          @Override
          public void run()
          {
            synchronized(this)
            {
                setMessageFromServer(connectClient());
                notify();
                
                System.out.println("FULL DATA:");
                System.out.println(getMessageFromServer());
            }
          }
    
          /**
           * http://www.dreamincode.net/forums/topic/139154-transfer-a-file-over-tcp/
           * @return Message received from the Server
           */
          public String connectClient()
          {
            String data = "";
            
            try
            {
                // Get IP Address and Port
                int serverPort = appSingleton.getIpPortShared();
                String ip = appSingleton.getIpAddressShared();
    
                // Create socket, input and output
                socket = new Socket(ip, serverPort);
                input = new DataInputStream( socket.getInputStream());
                output = new DataOutputStream( socket.getOutputStream());
    
                //Send message to the Server
                output.writeBytes(messageToServer);
    
                // ++++++++++++++++++++++++++++++
                //Read Response
                // ++++++++++++++++++++++++++++++
                
                br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    
                StringBuilder sb = new StringBuilder();
                String s = "";
    
                int value = 0;
                
                while((value = br.read()) != -1) 
                {
                    // converts int to character
                    char c = (char)value;
    
                    sb.append(c);
                    
                    if(sb.toString().contains(terminator))
                    {
                        break;
                    }
                }
    
                // Return data obtained from the Server
                data = sb.toString();
            }
    
            catch (UnknownHostException e)
            {
                String message = "Application was not able to establish connection.\n"
                        + "Check whether IP Address and Port number were correctly entered \n"
                        + "in Settings. Check whether connection is not being blocked by \n"
                        + "your firewall.";
                JOptionPane.showMessageDialog(new JFrame(), message, "TCP Connection Error",
                JOptionPane.ERROR_MESSAGE);
            }
    
            catch (EOFException e)
            {
                String message = "Application was not able to establish connection.\n"
                        + "Check whether IP Address and Port number were correctly entered \n"
                        + "in Settings. Check whether connection is not being blocked by \n"
                        + "your firewall.";
                JOptionPane.showMessageDialog(new JFrame(), message, "TCP Connection Error",
                JOptionPane.ERROR_MESSAGE);
            }
    
            catch (IOException e)
            {
                String message = "Application was not able to establish connection.\n"
                        + "Check whether IP Address and Port number were correctly entered \n"
                        + "in Settings. Check whether connection is not being blocked by \n"
                        + "your firewall.";
                JOptionPane.showMessageDialog(new JFrame(), message, "TCP Connection Error",
                JOptionPane.ERROR_MESSAGE);
            }
    
            finally 
            {
               // Needed??
            }
    
            return data;
          } 
        
        
          public void closeConnection()
          {
            try
            {
                System.out.println("CHECK WETHER CLOSING IS DONE HERE");
                    
                if(socket!=null)
                {
                    socket.close();
                }
                if(input != null)
                {
                    input.close();
                }
                if(output != null)
                {
                    output.close();
                }
                if(br != null)
                {
                    br.close();
                }
            }
            catch (IOException ex) 
            {
                Logger.getLogger(IGAConnectionTCP.class.getName()).log(Level.SEVERE, null, ex);
            }
                
            socket = null;
            input = null;
            output = null;
            br = null;
          }
    
          /**
           * Gets message to be sent from the Server.
           * @return Message to be sent from the Server.
           */
          public String getMessageFromServer() {
            return messageFromServer;
          }
    
          /**
           * Sets message to be sent from the Server.
           * @param messageFromServer Message to be sent from the Server.
           */
          public void setMessageFromServer(String messageFromServer) {
            this.messageFromServer = messageFromServer;
          }
     }
    My first problem is that the JDialog does not show the activity indicator and the "Please wait..." sign (basically, it is blank). I do not understand why, since it is called on the EDT.
    Secondly, when the error occurs, the JDialog is blank as well. I do know this is happening because of the threading problem. What would be the best way to move it to the EDT?

    Thank you!

  2. #2
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    13,541
    Rep Power
    25

    Default Re: TCP connection in the background thread. How to handle JDialogs?

    Since you are using Swing, don't use a Thread.
    Use a SwingWorker, which allows you to monitor progress and will inform the GUI when it's finished.

    The tutorial might help:
    https://docs.oracle.com/javase/tutor...cy/worker.html
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  3. #3
    igorland is offline Member
    Join Date
    Jan 2013
    Posts
    86
    Rep Power
    0

    Default Re: TCP connection in the background thread. How to handle JDialogs?

    Thanks a lot, Tolls!
    Last edited by igorland; 07-30-2017 at 05:38 PM.

  4. #4
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    6,174
    Rep Power
    12

    Default Re: TCP connection in the background thread. How to handle JDialogs?

    It appears you deleted your last post. Anyway, I tried this with a simulated transfer of data and it
    worked. I overrode the doInBackground() and process() methods. Another way to do this is to set
    up an AtomicInteger to hold the bytes transferred. Then invoke SwingUtilities.invokeLater() to execute
    your progress update call on the EDT. The amount of code is less than SwingWorker and should be
    sufficient for such a simple task.

    Regards,
    Jim
    Last edited by jim829; 07-31-2017 at 02:08 PM.
    igorland likes this.
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  5. #5
    igorland is offline Member
    Join Date
    Jan 2013
    Posts
    86
    Rep Power
    0

    Default Re: TCP connection in the background thread. How to handle JDialogs?

    Thank you, Jim. In the long run, this seems to work as intended:

    Java Code:
    public void sendMessage()
        {
            JFrame f = new JFrame();
            JDialog modalDialog = new JDialog(f, "Busy", Dialog.ModalityType.MODELESS);
            modalDialog.setSize(200, 100);
            modalDialog.setLocationRelativeTo(f);
            modalDialog.setUndecorated(true);
            modalDialog.getRootPane().setWindowDecorationStyle(JRootPane.NONE);
            modalDialog.getContentPane().setBackground( Color.WHITE );
            ImageIcon loading = new ImageIcon("src/images/activityIndicator.gif");
            modalDialog.add(new JLabel("Please wait... ", loading, JLabel.CENTER));
            modalDialog.setVisible(true);
    
            new Thread(() ->
            {
                String messageFromServer = connectClient(makeMessageToServer());
                        
                SwingUtilities.invokeLater(() ->
                {
                    modalDialog.setVisible(false);
                    modalDialog.dispose();
                            
                    // Show the message whether the connection worked
                    sentMessage(messageFromServer);
                });
            }).start();
            
        }
    Cheers.

  6. #6
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    6,174
    Rep Power
    12

    Default Re: TCP connection in the background thread. How to handle JDialogs?

    I haven't followed the logic of the above code but remember that SwingUtilities.invokeLater executes the supplied code on the EDT. So I'm not certain how the additional thread makes a difference.

    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

Similar Threads

  1. Replies: 0
    Last Post: 09-08-2014, 11:23 AM
  2. Single thread to handle queue based logging
    By impacted in forum Threads and Synchronization
    Replies: 5
    Last Post: 04-28-2011, 10:28 PM
  3. Single thread to handle queue based logging
    By impacted in forum New To Java
    Replies: 4
    Last Post: 04-28-2011, 10:25 PM
  4. best way to handle db connection
    By uthpalaw in forum Advanced Java
    Replies: 11
    Last Post: 02-18-2011, 06:00 AM
  5. how to handle data over two distinct socket connection
    By krishforever in forum New To Java
    Replies: 7
    Last Post: 02-03-2011, 10:57 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •