0

I have the following setup: First I have a GUI with Swift as my mainframe. Then I want to press a button and start a new Thread. If I press the button again the Thread should stop. The Thread is waiting for incomming TCP-Connection:

ServerSocket clientSocket = welcomeSocket.accept();

Now I tried to call in the GUI thread.interrupt(); to stop the Thread but it's not working due .accept is a blocking system call. What can I do to stop the Thread in waiting for a new connection? I don't want to use thread.stop() because it's deprecated.

Any solutions for it?

Gaston Flores
  • 2,457
  • 3
  • 23
  • 42
missjohanna
  • 293
  • 1
  • 2
  • 15

1 Answers1

0

You can use setSoTimeout(1000) to make the call to accept() time out after 1 second (by throwing a java.net.SocketTimeoutException) if nothing connects. Then you can check for a thread signal in a loop as follows:

try (ServerSocket serverSocket = new ServerSocket(8080)) {
    serverSocket.setSoTimeout(1000);
    //active is a volatile boolean manipulated by the control thread
    while (active) {
        try {
            Socket s = serverSocket.accept();
            somebodyConnected(s); //do something important here
        catch (java.net.SocketTimeoutException) {} //expected
    }
    System.out.println("exiting");
} //the try-with-resources ensures the ServerSocket is gracefully closed
Sean Reilly
  • 21,526
  • 4
  • 48
  • 62