How to stop a thread which is waiting for a client socket connection?
Created Oct 19, 2001
Sebastian Guzy [Short answer: you can't stop the thread, but you can close the socket, which causes accept to return. -Alex]
It may look like:
To start shutdown of your server you have to call the
Hope that I've understood you properly. So I assume, that you've got something like:
public class MyServer extends Thread {
// ...
private ServerSocket waitingSocket = null;
// ...
public void run() {
// ...
waitingSocket = new ServerSocket( serverSocketPortNumber );
while( yourAlwaysTrueCondition ) {
connectionSocket = waitingSocket.accept();
delegateInteractionWithClient( connectionSocket );
}
// ...
}
}
To be able to stop your server we have to implement:
-
possibility to call server for shutting down (
shutdown()method) -
end of waiting for incomming client connections (will be an
ifstatement in yourwhileloop)
It may look like:
public class MyServer extends Thread {
// ...
private ServerSocket waitingSocket = null;
// ...
private boolean shutdownRequested = false;
public void run() {
// ...
waitingSocket = new ServerSocket( serverSocketPortNumber );
while( yourAlwaysTrueCondition ) {
connectionSocket = waitingSocket.accept()
if( shutdownRequested==false ) {
delegateInteractionWithClient( connectionSocket );
}
else {
break;
}
}
// ...
}
public void shutdown() {
shutdownRequested = true;
new Socket(
waitingSocket.getInetAddress(),waitingSocket.getLocalPort()
).close();
}
}
To start shutdown of your server you have to call the
shutdown() method. It will
set shutdownRequested flag to true and force the accept()
method in your while loop to return. Since the shutdownRequested is true,
the break statement will be excecuted. And your server is down.