Im creating a server client program where client sends certain information to the server and get according response from the server.
For continuously listening from multiple clients I have a thread in server which continuously listens client request. whenever a request is received I start another thread and send that socket to run and start listening for other clients request.
here is the code for continuously listening
while(true){
//serverListener is a ServerSocket object
clientSocket = serverListener.accept();//Waiting for any client request
//New thread started when request is received from any client
Thread thread =new Thread(new serverThread(clientSocket), "ClientThread");
thread.start();
}
Now my problem is that how can i stop the server. I know one alternative of using a boo lean variable in while loop and then changing the value, but the problem is when where thread is in waiting to get any connection at that time changing value of the boolean variable will also not stop the server.
Is there any way to solve this problem.
ServerSocket#setSoTimeout() may of your interest, that will abandon accept if a timeout was reached. Be aware of catch the SocketTimeoutException.