I'm creating a multithread server that will receive message from client, process and send back the result.
The problem is when I want the server thread to stop, it won't.
Even setting the stopFlag=true
, the client is still can connect to server and get the result.
How can I stop the server thread(and may activate it later)?
I tried all of these below but they didn't work.
Java server socket program after one day it stops listening
Close listening ServerSocket http://tutorials.jenkov.com/java-multithreaded-servers/multithreaded-server.html
public class ServerStart implements Runnable{
private JTextArea servLog;
private boolean stopFlag=false;
public ServerStart(JTextArea servLog){
this.servLog=servLog;
}
public void setStopFlag(boolean stop){
stopFlag=stop;
}
@Override
public void run() {
int port=444;
try {
ServerSocket serverSock = new ServerSocket(port);
synchronized(this){
while(!stopFlag){
Socket clientSock=null;
try{
clientSock = serverSock.accept();
}catch(IOException e){
if(stopFlag){
System.out.println("Server stop");
return;
}
throw new RuntimeException("Error accepting client connection", e);
}
Thread listener = new Thread(new Socket_test(clientSock, port,servLog));
listener.start();
}
serverSock.close();
}
} catch (IOException ex) {
Logger.getLogger(ServerStart.class.getName()).log(Level.SEVERE, null, ex);
}
}
}