-1

I have a Runnable class which is waiting for a Socket connection. I want to add JButton that can cause it to stop waiting for the connection and come out of the loop.

Here is the loop

volatile boolean finished = false;

while (!finished) {
    System.out.println("Server Started....");
    clientSocket = serverSocket.accept();    // want to skip this line when the button is pressed
    if (!clientSocket.isClosed() && ServerSettings.getServerStatus() != -1) {
        // start communication
    } else {
        // close connection
    }
}

I looked for this issue and found a solution here to exit the loop. But this does not completely solve my problem. I can change the value of finished variable, but to check the new value I still need to skip the waiting once.

Any help is appreciable.

Community
  • 1
  • 1
me_digvijay
  • 5,374
  • 9
  • 46
  • 83

2 Answers2

0

You can call close() method. This will stop the wainting of connections.

Masudul
  • 21,823
  • 5
  • 43
  • 58
0

Instead of ServerSocket, use ServerSocketChannel, it's accept() method does not block. From documentation:

public abstract SocketChannel accept() throws IOException

Accepts a connection made to this channel's socket.

If this channel is in non-blocking mode then this method will immediately return null if there are no pending connections.

Community
  • 1
  • 1
uiron
  • 890
  • 11
  • 14