我想关闭 HTTP线程服务器。为此,我创建了一个正在监听STDIN的线程。
如果我输入shutdown
,它会关闭服务器。
代码
public class WebServerShutdown extends Thread{
Logger log = Logger.getLogger( WebServerShutdown.class.getName() );
@Override
public void run() {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
//ThreadPool threadpool = new ThreadPool();
String s;
while ((s = in.readLine()) != null && s.length() != 0) {
System.out.println(s);
if(s.equalsIgnoreCase("shutdown")) {
ThreadPool.isStopped = true;
break;
}
}
} catch (IOException ex) {
log.info(new Date() + " Problem in reading Input from keyboard");
}
System.out.println("Thread comes out");
}
}
服务器侦听的代码
while( !(ThreadPool.isStopped) ) {
Socket client_socket = null;
try {
System.out.println("try to accept socket");
client_socket = serversocket.accept();
} catch(IOException ie) {
log.info(new Date() + " Server Stopped");
}
ThreadPool.threads.execute(new Worker(client_socket));
}
System.out.println("Reached here");
ThreadPool.threads.shutdown();
serversocket.close();
log.info(new Date() + " WEBSERVER STOPPED");
但是当我写关闭时,有一个问题,那时服务器进入循环并监听客户端的请求。所以,当我提出任何客户请求时,它会关闭服务器。
但这并不好。我想每当我写关机时,它都不会接受任何其他客户端请求。
帮我制作上面的代码。
答案 0 :(得分:0)
您必须调用ServerSocket的Close()
方法,但在该线程之外。当你调用该方法时,你会在accept()
中抛出一个IOException,然后你调用break;
来停止那个循环。
if(s.equalsIgnoreCase("shutdown")) {
ThreadPool.isStopped = true;
ClassListening.ServerSocket.close();
break;
}
// Break the loop where the ServerSocket was listening
try {
System.out.println("try to accept socket");
client_socket = serversocket.accept();
} catch(IOException ie) {
log.info(new Date() + " Server Stopped");
break;
}
答案 1 :(得分:0)
当serversocket closes
套接字时,accept
异常应该被SocketException
捕获,如下所示,
WebServerShutdown类
@Override
public void run() {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String s;
while ((s = in.readLine()) != null) {
System.out.println(s);
if(s.equalsIgnoreCase("shutdown")) {
ThreadPool.isStopped = true;
break;
}
}
} catch (IOException ex) {
log.info(new Date() + " Problem in reading Input from keyboard");
}
System.out.println("Thread comes out");
try {
WebServer.serversocket.close();
} catch(IOException ie) {
log.info(new Date() + " Problem in closing socket");
}
}
服务器侦听的代码
while( !(ThreadPool.isStopped) ) {
Socket client_socket = null;
try {
client_socket = serversocket.accept();
} catch(SocketException se) {
log.info(new Date() + " WEBSERVER STOPPED");
}
if(ThreadPool.isStopped) break;
ThreadPool.threads.execute(new Worker(client_socket));
}