我有这个Java Swing应用程序,它会启动一个新线程,每次传入客户端尝试建立连接时,该线程都会使用执行程序池来打开套接字服务器.
该应用程序需要两个按钮,一个按钮启动,另一个按钮停止服务器.我想要的是显示服务器状态,并禁用相反的按钮,直到其状态更改为止.
这是我现在拥有的,但是我不知道线程停止时如何与EDT通信.我所能做的就是检查isRunning()方法.
使用SwingWorker会更好吗?
public class ServerManager implements Runnable {
private Executor mExecutor = Executors.newSingleThreadExecutor();
private ServerSocket mServerSocket = null;
private int mDefaultPort = 43012;
private volatile boolean isRunning = false;
public ServerManager (int port){
mDefaultPort = port;
}
@Override
public void run() {
try {
mServerSocket = new ServerSocket(mDefaultPort);
isRunning = true;
while (isRunning){
mExecutor.execute(new IncomingClientThread(mServerSocket.accept()));
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if(mServerSocket != null){
stop();
System.out.println("Server closed");
}
}
}
public void stop(){
try {
mServerSocket.close();
isRunning = false;
} catch (IOException e) {
throw new RuntimeException("Error closing server", e);
}
}
public synchronized boolean isRunning() {
return isRunning;
}
public int getServerPort (){
return mDefaultPort;
}
}
这就是我在GUI线程中所拥有的:我仅使用一个按钮并在每次按下按钮时更改其文本,但是如果服务器由于某种原因断开连接,则该按钮保持不变.
connectButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if(mServer.isStopped()){
new Thread (mServer).start();
connectButton.setText("Desconectar");
infoLabel.setText("Servidor online en IP: " + NetworkUtils.getLocalIpAddress()
+ " puerto: " + mServer.getServerPort());
System.out.println(mServer.getIpAddress());
}else{
mServer.stop();
connectButton.setText("Conectar");
infoLabel.setText("Offline");
}
}
});
任何帮助都很好!
谢谢.