Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/blackberry/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
我能';t停止java SwingWorker进程_Java_Multithreading_Swing_Swingworker_Tcpserver - Fatal编程技术网

我能';t停止java SwingWorker进程

我能';t停止java SwingWorker进程,java,multithreading,swing,swingworker,tcpserver,Java,Multithreading,Swing,Swingworker,Tcpserver,我在java中运行tcp服务器,这是使用SwingWorker类完成的。第一次它将开始成功,但当我停止并开始这个过程时,它将不起作用。我找不到什么错误,请帮我解决这个问题 import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.BufferedReader; import java.io.IOEx

我在java中运行tcp服务器,这是使用SwingWorker类完成的。第一次它将开始成功,但当我停止并开始这个过程时,它将不起作用。我找不到什么错误,请帮我解决这个问题

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

public class SwingWorkerDemo extends JFrame {
     /**
     * 
     */
    private static final long serialVersionUID = 1L;
    private static ServerSocket serverSocket;
        private static Socket clientSocket;
        private static InputStreamReader inputStreamReader;
        private static BufferedReader bufferedReader;
        private static String message;

    public SwingWorkerDemo() {
        initialize();
    }

    private void initialize() {
        this.setLayout(new FlowLayout());
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        final JButton startButton = new JButton("Start");
        final JButton stopButton = new JButton("Stop");
        final LongRunProcess process = new LongRunProcess();



        startButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent event) {
                try {
                    process.execute();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                startButton.setEnabled(false);
                stopButton.setEnabled(true);
            }
        });

        stopButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
               // JOptionPane.showMessageDialog(null, "Hello There");

process.cancel(true);
startButton.setEnabled(true);
stopButton.setEnabled(false);
            }
        });


        this.getContentPane().add(startButton);
        this.getContentPane().add(stopButton);

        this.pack();
        this.setSize(new Dimension(300, 80));
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new SwingWorkerDemo().setVisible(true);
            }
        });
    }

    class LongRunProcess extends SwingWorker {
        /**
         * @throws Exception
         */
        protected Object doInBackground() throws Exception {
            try {
                serverSocket = new ServerSocket(4545);  //Server socket

            } catch (IOException e) {
                System.out.println("Could not listen on port: 4545");
            }

            System.out.println("Server started. Listening to the port 4545");

            while (true) {
                try {

                    clientSocket = serverSocket.accept();   //accept the client connection
                    inputStreamReader = new InputStreamReader(clientSocket.getInputStream());
                    bufferedReader = new BufferedReader(inputStreamReader); //get the client message
                    message = bufferedReader.readLine();
     if(message.equals("shutdown")){

    Runtime runtime = Runtime.getRuntime();
    Process proc = runtime.exec("shutdown -s -t 00");
    System.exit(0);

     }
     else if(message.equals("restart")){
    Runtime runtime1 = Runtime.getRuntime();
    Process proc2 = runtime1.exec("shutdown -r -t 00");
    System.exit(0);


     }

                    System.out.println(message);
                    inputStreamReader.close();
                    clientSocket.close();

                } catch (IOException ex) {
                    System.out.println("Problem in message reading");
                }
            }

    }
    }
}
根据

注意:SwingWorker仅设计为执行一次。执行 SwingWorker多次不会导致调用 做两次背景法

因此,你所看到的行为。所以,为了实现你所期待的。每次按下“开始”按钮时,都需要创建
LongRunProcess
的新实例。像这样的

在类级别声明

LongRunProcess process = null;
修改操作侦听器

 startButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            try {
                process = new LongRunProcess();
                process.execute();
            } catch (Exception e) {
                e.printStackTrace();
            }
            startButton.setEnabled(false);
            stopButton.setEnabled(true);
        }
    });
希望这有帮助。

根据

注意:SwingWorker仅设计为执行一次。执行 SwingWorker多次不会导致调用 做两次背景法

因此,你所看到的行为。所以,为了实现你所期待的。每次按下“开始”按钮时,都需要创建
LongRunProcess
的新实例。像这样的

在类级别声明

LongRunProcess process = null;
修改操作侦听器

 startButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            try {
                process = new LongRunProcess();
                process.execute();
            } catch (Exception e) {
                e.printStackTrace();
            }
            startButton.setEnabled(false);
            stopButton.setEnabled(true);
        }
    });

希望这有帮助。

你可以用这个。在这方面,我也做了一些改变

public class Test extends JFrame {
    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    private static ServerSocket serverSocket;
    private static Socket clientSocket;
    private static InputStreamReader inputStreamReader;
    private static BufferedReader bufferedReader;
    private static String message;

    public Test() {
        initialize();
    }

    LongRunProcess process;

    private void initialize() {
        this.setLayout(new FlowLayout());
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        final JButton startButton = new JButton("Start");
        final JButton stopButton = new JButton("Stop");

        startButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent event) {
                try {
                    process = new LongRunProcess();
                    process.start();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                startButton.setEnabled(false);
                stopButton.setEnabled(true);
            }
        });

        stopButton.addActionListener(new ActionListener() {
            @SuppressWarnings("deprecation")
            public void actionPerformed(ActionEvent e) {
                // JOptionPane.showMessageDialog(null, "Hello There");

                process.closeServer();

                startButton.setEnabled(true);
                stopButton.setEnabled(false);
                process.stop();
            }
        });

        this.getContentPane().add(startButton);
        this.getContentPane().add(stopButton);

        this.pack();
        this.setSize(new Dimension(300, 80));
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new Test().setVisible(true);
            }
        });
    }

    class LongRunProcess extends Thread {
        /**
         * @throws Exception
         */
        public void closeServer() {
            try {
                serverSocket.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            System.out.println("Closed Now");
        }

        public void run() {
            try {
                serverSocket = new ServerSocket(4545); // Server socket

            } catch (IOException e) {
                System.out.println("Could not listen on port: 4545");
            }

            System.out.println("Server started. Listening to the port 4545");

            while (!(serverSocket.isClosed())) {
                try {

                    clientSocket = serverSocket.accept(); // accept the client
                                                            // connection
                    inputStreamReader = new InputStreamReader(
                            clientSocket.getInputStream());
                    bufferedReader = new BufferedReader(inputStreamReader); // get
                                                                            // the
                                                                            // client
                                                                            // message
                    message = bufferedReader.readLine();
                    if (message.equals("shutdown")) {

                        Runtime runtime = Runtime.getRuntime();
                        Process proc = runtime.exec("shutdown -s -t 00");
                        System.exit(0);

                    } else if (message.equals("restart")) {
                        Runtime runtime1 = Runtime.getRuntime();
                        Process proc2 = runtime1.exec("shutdown -r -t 00");
                        System.exit(0);

                    }

                    System.out.println(message);
                    inputStreamReader.close();
                    clientSocket.close();

                } catch (IOException ex) {
                    System.out.println("Problem in message reading");
                }
            }
        }
    }
}

你可以用这个。在这方面,我也做了一些改变

public class Test extends JFrame {
    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    private static ServerSocket serverSocket;
    private static Socket clientSocket;
    private static InputStreamReader inputStreamReader;
    private static BufferedReader bufferedReader;
    private static String message;

    public Test() {
        initialize();
    }

    LongRunProcess process;

    private void initialize() {
        this.setLayout(new FlowLayout());
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        final JButton startButton = new JButton("Start");
        final JButton stopButton = new JButton("Stop");

        startButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent event) {
                try {
                    process = new LongRunProcess();
                    process.start();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                startButton.setEnabled(false);
                stopButton.setEnabled(true);
            }
        });

        stopButton.addActionListener(new ActionListener() {
            @SuppressWarnings("deprecation")
            public void actionPerformed(ActionEvent e) {
                // JOptionPane.showMessageDialog(null, "Hello There");

                process.closeServer();

                startButton.setEnabled(true);
                stopButton.setEnabled(false);
                process.stop();
            }
        });

        this.getContentPane().add(startButton);
        this.getContentPane().add(stopButton);

        this.pack();
        this.setSize(new Dimension(300, 80));
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new Test().setVisible(true);
            }
        });
    }

    class LongRunProcess extends Thread {
        /**
         * @throws Exception
         */
        public void closeServer() {
            try {
                serverSocket.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            System.out.println("Closed Now");
        }

        public void run() {
            try {
                serverSocket = new ServerSocket(4545); // Server socket

            } catch (IOException e) {
                System.out.println("Could not listen on port: 4545");
            }

            System.out.println("Server started. Listening to the port 4545");

            while (!(serverSocket.isClosed())) {
                try {

                    clientSocket = serverSocket.accept(); // accept the client
                                                            // connection
                    inputStreamReader = new InputStreamReader(
                            clientSocket.getInputStream());
                    bufferedReader = new BufferedReader(inputStreamReader); // get
                                                                            // the
                                                                            // client
                                                                            // message
                    message = bufferedReader.readLine();
                    if (message.equals("shutdown")) {

                        Runtime runtime = Runtime.getRuntime();
                        Process proc = runtime.exec("shutdown -s -t 00");
                        System.exit(0);

                    } else if (message.equals("restart")) {
                        Runtime runtime1 = Runtime.getRuntime();
                        Process proc2 = runtime1.exec("shutdown -r -t 00");
                        System.exit(0);

                    }

                    System.out.println(message);
                    inputStreamReader.close();
                    clientSocket.close();

                } catch (IOException ex) {
                    System.out.println("Problem in message reading");
                }
            }
        }
    }
}

我没有看到任何试图关闭服务器套接字的痕迹。如何从UI线程停止它?您是否已尝试调用
.close()
?您是指Longrunprocess.close()?这取决于你的代码。如果要将其放入一个方法中并命名为该方法
close
,没有什么可以阻止您。我没有看到任何试图关闭服务器套接字的痕迹。如何从UI线程停止它?您是否已经尝试调用
.close()
?您是指Longrunprocess.close()?这取决于你的代码。如果你想把它放在一个方法中,并把它命名为方法
close
,没有什么能阻止你。我不是想以串行方式执行它,我只是想启动-停止过程,所以通常一次只运行一个swingworker是的,但是你在初始化方法中只创建了一次LongRunProcess实例,因此,您正试图一次又一次地重复使用同一实例。你必须在按下开始按钮后创建一个新的LongRunProcess实例。但是我如何在关闭打开的端口的情况下停止当前正在运行的进程,否则它将抛出一个异常端口正在使用我不尝试以串行方式执行它我只想要启动-停止过程,所以通常一次只运行一个swingworker是的,但是您在初始化方法中只创建了一次LongRunProcess实例,所以您试图一次又一次地重复使用同一实例。您必须在按下开始按钮后创建一个新的LongRunProcess实例。但是,如何在关闭打开的端口的情况下停止当前正在运行的进程,否则它将抛出一个异常端口正在使用