2015-04-29 121 views
0

我想使用Restlet来创建本地服务器。这个服务器应该接收一个请求(除favicon之外),并且在处理请求之后它应该关闭。我不想使用System.exit,我想让它正常关闭。在处理完一个请求后,Restlet停止服务器

正如你在我的代码中看到的,当我假设请求被正确处理时,我评论了该行。但我无法告诉服务器停在那里。

我该如何告诉服务器停止等待请求? 我得到它的工作,但有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(); 
        } 
    } 
    
    } 
    

回答

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(); 

    } 

} 
+0

是的,我认为实现这种功能的方式;-) –

相关问题