我想使用Restlet来创建本地服务器。此服务器应该接收exaclty一个请求(除了favicon),并且在处理该请求之后它应该关闭。我不想使用System.exit
,我希望它能够正常关闭。
正如您在我的代码中所看到的,当我假设请求得到正确处理时,我对该行进行了评论。但我无法告诉服务器停在那里。
如何告诉服务器此时停止等待请求? 我得到了它的工作,但有2个问题,我想解决。
如果我在请求中停止服务器,则不会显示发送到客户端的response
public class Main {
public static void main(String[] args){
Server serv = null;
Restlet restlet = new Restlet() {
@Override
public void handle(Request request, Response response) {
if(!request.toString().contains("favicon")){
System.out.println("do stuff");
response.setEntity("Request will be handled", MediaType.TEXT_PLAIN);
//stop server after the first request is handled.
//so the program should shut down here
//if I use serv.stop() here (besides it's currently not final)
//I'd get exceptions and the user wouldn't see the response
}
}
};
// Avoid conflicts with other Java containers listening on 8080!
try {
serv = new Server(Protocol.HTTP, 8182, restlet);
serv.start();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
答案 0 :(得分:1)
我想出了办法。在响应中添加OnSent
事件,并在此处关闭服务器。
public class Main {
private Server serv;
public Main(){
run();
}
public void run(){
Restlet restlet = new Restlet() {
@Override
public void handle(Request request, Response response) {
response.setEntity("Request will be handled", MediaType.TEXT_PLAIN);
if(!request.toString().contains("favicon")){
System.out.println("do stuff");
response.setOnSent(new Uniform() {
@Override
public void handle(Request req, Response res) {
try {
serv.stop();//stop the server
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
}
};
// Avoid conflicts with other Java containers listening on 8080!
try {
serv = new Server(Protocol.HTTP, 8182, restlet);
serv.start();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args){
new Main();
}
}