?
Solved

Server Socket + Thread Problem with GUI

Posted on 2005-05-05
8
Medium Priority
?
233 Views
Last Modified: 2008-01-09
Hi,

I have a problem with the code below. I have created the file with a GUI and when the user clicks the start button the button calls a main1 method, which subsequently loops in a while(true) and creates the threads for sending and receiving. However, once the button is clicked the GUI hangs, whilst if I try and create and call a thread from the start button that utilises the attributes within the main1 method it does not work either. So I am after some help if possible.

Cheers

import java.util.*;
import javax.swing.* ;
import java.awt.* ;
import java.awt.event.* ;
import java.io.*;
import java.util.*;
import java.net.*;

class Server extends JFrame
{  

      private JTextField textField1, serverAddress, port ;
    public JTextArea textOutput, messageArea ;
    private JLabel serverLabel, portLabel ;
    private JButton startButton, stopButton, monitorButton, exitButton ;
    String ip ;
   
    ServerSocket serverSocket ;
    Socket userSocket ;
    StartServerThread startThis ;
      
      public Server () throws  UnknownHostException,InterruptedException,ClassNotFoundException,IOException
    {
   
    super ("ChatMessage Server") ;
          int portNum = 1234;
          serverSocket = new ServerSocket(portNum);
          //userSocket = serverSocket.accept();
        Container container = getContentPane () ;            //Creates a container for the JFrame
           container.setLayout (new FlowLayout ()) ;            //Create a layout for the JFrame
         
        startButton = new JButton ("Start Server") ;
          startButton.addActionListener(
                
          new ActionListener() {
                
          public void actionPerformed (ActionEvent event)
        {
              
              try
              {
                    main1 () ;  /////////////////////////////not working
                                  
              }
              
              
                 catch(IOException e)
                 {
                       
                 }
                 catch(ClassNotFoundException e)
                 {
                       
                 }
                 catch(InterruptedException e)
                 {
                       
                 }
                 catch(NullPointerException e)
                 {
                       //JOptionPane.showMessageDialog(null,"Unable to send please connect to server","Server Error", JOptionPane.INFORMATION_MESSAGE) ;
                 }
        }
            });
            
            container.add (startButton) ;  
       
        stopButton = new JButton ("Stop Server") ;
          stopButton.addActionListener(
                
          new ActionListener() {
                
          public void actionPerformed (ActionEvent event)
        {
              try
              {
                    serverSocket.close () ;
                    System.out.println("Server stopped") ;
              }
              
              
                 catch(IOException e)
                 {
                       
                 }
                 
                 catch(NullPointerException e)
                 {
                       //JOptionPane.showMessageDialog(null,"Unable to send please connect to server","Server Error", JOptionPane.INFORMATION_MESSAGE) ;
                 }
        }
            });
            
            container.add (stopButton) ;
            
            monitorButton = new JButton ("Monitor User") ;
          monitorButton.addActionListener(
                
          new ActionListener() {
                
          public void actionPerformed (ActionEvent event)
        {
              String input = JOptionPane.showInputDialog ("Please enter the user name you wish to block") ;
        }
            });
            
            container.add (monitorButton) ;
            
        serverLabel = new JLabel ("Server Address    ") ;
        container.add (serverLabel) ;
         
          serverAddress = new JTextField (10) ;
          serverAddress.setEditable (false) ;
          serverAddress.setText("127.0.0.1" );
          container.add (serverAddress) ;
            
          portLabel = new JLabel ("Port    ") ;
          container.add (portLabel) ;
          
          port = new JTextField (3) ;
          port.setEditable (false) ;
          port.setText("1234") ;
          container.add (port) ;
          
          textOutput = new JTextArea (15,50) ;
            textOutput.setWrapStyleWord (true);
            textOutput.setLineWrap (true) ;
            textOutput.setEditable (false) ;
            container.add(new JScrollPane(textOutput)) ;
            
            messageArea = new JTextArea (5,50) ;
            messageArea.setWrapStyleWord (true);
            messageArea.setLineWrap (true) ;
            messageArea.setEditable (true) ;
            container.add(new JScrollPane(messageArea)) ;
   
          setBounds (200,200,580,500) ;
            setSize (680,525) ;
            setVisible (true) ;
    }
    public void main1() throws IOException,
                                                  StreamCorruptedException,
                                                  ClassNotFoundException, InterruptedException, NullPointerException
   {
   
               Vector msgs_data_structure = new Vector (10,10) ;;
        while (true)
        {
              System.out.println("Server started") ;
            Socket userSocket = serverSocket.accept();
            ServerReceivingThread receive = new ServerReceivingThread (userSocket, msgs_data_structure, textOutput);      // create a thread for this user
            ServerSendingThread send = new ServerSendingThread (userSocket, msgs_data_structure, receive, textOutput);      // create a thread for this user
            receive.start();      // start a thread for this user
            send.start () ;
                  System.out.println("Done") ;

        }
   }
   
   public String  getIP ()
   {
               try
               {
               
               InetAddress me = InetAddress.getLocalHost();
               ip = me.getHostAddress() ;
               }
               catch(UnknownHostException e)
               {
               }
               return ip ;
   }
 
}
0
Comment
Question by:Cyart
  • 5
  • 3
8 Comments
 
LVL 92

Expert Comment

by:objects
ID: 13940826
Swing is single threaded so any long task on that thread will block the gui
Use the SwingWorker class to handle long tasks
0
 

Author Comment

by:Cyart
ID: 13940979
Objects,

thanx for the reply do I have to return anything or will it work without returning. I keep getting "cannot find symbol" error for the following line

final SwingWorker worker = new SwingWorker() {


I took this code off of the site you specified

public void actionPerformed(ActionEvent e)
          {
   
                final SwingWorker worker = new SwingWorker() {
                    public Object construct() {
            //...code that might take a while to execute is here...
            return someValue;
        }
};

Can I do this for the code I listed for the startButton previously?


startButton = new JButton ("Start Server") ;
          startButton.addActionListener(
                
          new ActionListener() {
                
          public void actionPerformed(ActionEvent e)
          {
   
                final SwingWorker worker = new SwingWorker() {
                    public void construct() {
                                 main1  () ;
        }
    };
    worker.start();  //required for SwingWorker 3
   }
0
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
LVL 92

Expert Comment

by:objects
ID: 13940998
No you don't need to return anything.
you can download the SwingWorker class at
http://java.sun.com/products/jfc/tsc/articles/threads/src/SwingWorker.java
0
 

Author Comment

by:Cyart
ID: 13941068
Object,

Thanks for the help, I have copied the StringWorker class and it seams to work OK but have not tested the client connections yet. I assume I do not need to deal with the returned object if I dont want to. This was the code I used does it look OK to you?

startButton.addActionListener(
                
          new ActionListener() {
                
          public void actionPerformed(ActionEvent e)
          {
   
                final SwingWorker worker = new SwingWorker() {
                    public Object construct() {
           
            try
              {
                    
                    main1 () ;
                    /
              
              }
              
              
                 catch(IOException e)
                 {
                       
                 }
                 catch(ClassNotFoundException e)
                 {
                       
                 }
                 catch(InterruptedException e)
                 {
                       
                 }
                 catch(NullPointerException e)
                 {
                       //JOptionPane.showMessageDialog(null,"Unable to send please connect to server","Server Error", JOptionPane.INFORMATION_MESSAGE) ;
                 }
            return someValue;
        }
    };
    worker.start();  //required for SwingWorker 3
   }
0
 
LVL 92

Accepted Solution

by:
objects earned 1000 total points
ID: 13941122
looks about right :)
0
 

Author Comment

by:Cyart
ID: 13950290
Objects,

Thanx for your help.
0
 
LVL 92

Expert Comment

by:objects
ID: 13952272
no worries :)
0

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction This article is the last of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers our test design approach and then goes through a simple test case example, how …
In this post we will learn how to make Android Gesture Tutorial and give different functionality whenever a user Touch or Scroll android screen.
Video by: Michael
Viewers learn about how to reduce the potential repetitiveness of coding in main by developing methods to perform specific tasks for their program. Additionally, objects are introduced for the purpose of learning how to call methods in Java. Define …
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…
Suggested Courses
Course of the Month13 days, 10 hours left to enroll

750 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question