在下面的代碼中,我試圖啓動和停止服務器上的按鈕使用java applet.Start工作良好使用線程,但我想停止按鈕上的服務器。我已經使用揮發性 variable.Still我沒有得到服務器停止..線程不停止使用標誌作爲易失性
這裏是代碼:
public class TCPServer extends Thread {
public static final int SERVERPORT = 8002;
private boolean running = false;
public volatile boolean stop = false;
public Socket client = null;
public static void main(String[] args) {
ServerBoard frame = new ServerBoard();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
public void run() {
super.run();
running = true;
try {
System.out.println("Server Has Started........ \n Waiting for client........");
ServerSocket serverSocket = new ServerSocket(SERVERPORT);
try {
while (!stop && running) {
client = serverSocket.accept();
System.out.println("Connection Accepted......");
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
String usercmnd = in.readLine();
if (usercmnd != null) {
Runtime runtime = Runtime.getRuntime();
Process p = runtime.exec(usercmnd);
}
}
if (stop) {
serverSocket.close();
client.close();
System.out.println("Server Has Stopped");
System.exit(0);
}
} catch (Exception e) {
System.out.println("Error");
e.printStackTrace();
}
} catch (Exception e) {
System.out.println("Error");
e.printStackTrace();
}
}
public void requestStop() {
stop = true;
}
}
但每當我點擊停止按鈕,將停止沒有表現出任何的server.Its在控制檯輸出如我所料由code.Its也沒有表現出任何錯誤 這裏是停止按鈕的代碼
stopServer = new JButton("Stop");
stopServer.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
stopServer.setEnabled(false);
startServer.setEnabled(true);
mServer = new TCPServer();
mServer.requestStop();
}
});
我猜想它不會停止,因爲'serverSocket.accept()'阻塞。嘗試在'requestStop'中關閉'serverSocket'。 –
'stop'和'running'有什麼區別? –
@AndyTurner其顯示SocketException:套接字關閉, –