我在java中運行一個使用SwingWorker類的tcp服務器。第一次它會開始成功,但是當我停下來並開始這個過程時,它將無法工作。我找不到什麼漏洞,請幫我解決這個我無法停止Java 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");
}
}
}
}
}
我看不到任何關閉服務器套接字嘗試的跟蹤。 –
我如何阻止它從UI線程? –
您是否已經嘗試調用'.close()'? –