How to stop a thread which is waiting for a client socket connection?

Sebastian Guzy

[Short answer: you can't stop the thread, but you can close the socket, which causes accept to return. -Alex]

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 if statement in your while loop)

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.

0 Comments  (click to add your comment)
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

About | Sitemap | Contact