I’m writing a multi-threaded server application in Java.
Everything works fine , but there’s one little problem.
When I’m stopping the runnable which listens for incoming connection request , the socket keeps existing . So my question is : How do I stop a runnable object and clean up all the objects made in this runnable ?
The code for stopping the thread:
Runnable tr = new Worldwide() ;
Thread thread = new Thread(tr) ;
thread.start() ;
online = true ;
while (core.getServerSate()) {
try{
Thread.sleep(200);
} catch (Exception e ) {
e.printStackTrace();
}
} ;
thread.stop() ;
thread.
core.printToConsole("Server is offline now") ;
The Runnable code :
public class Worldwide implements Runnable {
Core core = Core.getInstance() ;
public Worldwide () {
}
@Override
public void run() {
try {
ServerSocket server = new ServerSocket(port) ;
core.printToConsole("Server is online") ;
core.printToConsole ( "listening on port :" + server.getLocalPort()) ;
while (core.getServerSate() == true) {
Socket client = server.accept() ;
Runnable tr = new ClientCommunication(client) ;
new Thread (tr).start() ;
}
}
catch(Exception e ) {
core.printToConsole ("An error occured while going online") ;
e.printStackTrace() ;
}
}
Thanks , Tom
You can close the socket from the main thread. This will break the call to
acceptand cause it to throw anIOException. You can then exit the accept thread’srunmethod from the catch of theIOException.