Link to home
Start Free TrialLog in
Avatar of Cyart
CyartFlag for United Kingdom of Great Britain and Northern Ireland

asked on

Server Socket + Thread Problem with GUI

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 ;
   }
 
}
Avatar of Mick Barry
Mick Barry
Flag of Australia image

Swing is single threaded so any long task on that thread will block the gui
Use the SwingWorker class to handle long tasks
Avatar of Cyart

ASKER

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
   }
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
Avatar of Cyart

ASKER

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
   }
ASKER CERTIFIED SOLUTION
Avatar of Mick Barry
Mick Barry
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Cyart

ASKER

Objects,

Thanx for your help.
no worries :)