I am writing a server application in Java where i have in an activation method of MyServer class:
System.out.println("The Base Station was activated");
Socket s; //Here it listens for new connections
this.server = new ServerSocket(this.getPort());
while(activated == true)
{
s = this.server.accept();
ClientHandler ch = new ClientHandler(s);
Thread servingThread = new Thread(ch);
servingThread.start();
}
It is waiting for clients to connect and it spawns a thread to accommodate each client. I also want to support a deactivation button in my GUI, but i can’t see how the ActionListener for that button, which is defined in a MyServerFrame class, can ever be called and change the status of activated variable if the above server code is stuck waiting in accept. How can i overcome this problem?
You will have to give access to the server socket inside the class holding the stop button handler (for example by passing the MyServer instance to the MyServerFrame instance) and inside the handler close the socket, such that the call to accept returns and then you can exit the while loop.
So inside the handler you should be able to do: