2

I have created a simple HTTP server in Java by using a ServerSocket that accepts browser requests. The server is working fine without any errors. I have created a JForm using Swing that contains buttons to start and stop the server. In the start button I have added an ActionListener that runs my ServerMain class.

btnStartServer.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
    try {
        new Thread(new Runnable() {
            public void run() { 
                ServerMain.main(new String[0]);
            }
         }).start();
        } catch (Exception e) {
        e.printStackTrace();
    }
}});

How will I be able to create a Stop JButton which will stop the Runnable() thread?

  • Can you share ServerMain.main() code? – Noor Nawaz Feb 07 '16 at 03:42
  • There's no guaranteed way of stopping a `Thread` other then to program the code in thread to support it. Your server should be monitoring the interrupted state of the current thread and you should have a flag (probably an `AtomicBoolean`) that you can change and check the state of to determine of the thread – MadProgrammer Feb 07 '16 at 04:40

2 Answers2

2

Run the server in the context of a class that implements the cancel() method of Future<V>. SwingWorker<T,V> is such a RunnableFuture<V>; a complete example is seen here.

Community
  • 1
  • 1
trashgod
  • 203,806
  • 29
  • 246
  • 1,045
1

You don't want to just kill a thread (by using Thread.stop()). The reasons why are listed in this article.

I assume the code in ServerMain.main(String... args) runs some kind of while(condition) loop, like this:

public class ServerMain{
    public static boolean condition = true;

    public static void main(String... args){
        while(condition){
            //do stuff
        }
        //close sockets and other streams.
        //Call Thread.interupt() on all sleeping threads
    }
}

Your button should set this condition to false somehow:

stopButton.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent ae) {
        try {
            new Thread() {
                public void run() {
                    // set condition to false;
                    ServerMain.condition = false;
                }
            }.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
});
Neuron
  • 5,141
  • 5
  • 38
  • 59