java - How can I stop the server thread(and may activate it later)? -
i'm creating multithread server receive message client, process , send result.
the problem when want server thread stop, won't.
even setting stopflag=true
, client still can connect server , result.
how can stop server thread(and may activate later)?
i tried of these below didn't work.
java server socket program after 1 day 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); } }
}
you need interrupt socket accept()
method waiting on read client. timeout on accept do, or calling close() thread
secondly, stoprun
variable should volatile can seen on other threads when updated.
Comments
Post a Comment