The core code of the server is as follows:
@ Override public void receivedata () throws ioexception {// todo auto-generated method stub recthread = new recthread (); crtthread = new thread (recthread); crtthread. start ();} class recthread implements runnable {public void run () {try {Listen ();} catch (ioexception e) {e. printstacktrace () ;}}// listens to client connections and data public void listen () throws ioexception {system. out. println ("START"); While (threadflag) {If (threa Dflag) {selector. select (); set <selectionkey> selectionkeys = selector. selectedkeys (); iterator = selectionkeys. iterator (); While (iterator. hasnext () {selectionkey = (selectionkey) iterator. next (); handlekey () ;}} if (selectionkey! = NULL) {selectionkey. Cancel ();} selector. Close ();}
Then execute receivedata () to start the thread for listening. When closing the program, you only need to set threadflag to false before closing the program so that the thread can exit automatically.
After testing, I found that if the client and server have established a connection and communicated, you can use the above method to completely close the program,
If only the service end starts the listening thread and no client is connected, javaw.exe is still running in the background after the service end is closed. Although the thread running mark threadflag is set to false, it is clear that the thread is still running.
I don't understand it when I am running it. Later I studied it and found that as long as there is selector in the thread code. select (); then this thread cannot be closed, and there is no way to use it.
Runtime rt = Runtime.getRuntime(); String command = "taskkill /F /IM javaw.exe"; try { rt.exec(command); System.out.println("success closed"); } catch (IOException ex) { ex.printStackTrace(); }
This stupid method completely closes the program ......