2015-06-27 127 views
3

我在应用程序内部有简单的nanohttpd服务器实现,当它以常规方式运行时,它工作正常(java -jar myApp.jar)。但是当我试图将其作为后台进程运行时,nanohttpd没有得到http请求,浏览器只是查找并从未收到响应。在日志文件中也没有消息,我仅在服务器启动时发出消息:Server started, Hit Enter to stop.不能在后台使用内置的nanohttpd服务器运行jar(使用nohup)

我用来在后台运行我的应用程序的命令:nohup java -jar myApp.jar &我也尝试了很多不同的变体,在日志中写入等(即nohup java -jar myApp.jar >myApp.log 2>&1 &)。

代码我的服务器类:我的主类的

public class WebServer extends NanoHTTPD { 

public static final String JSON_STATUS = "status"; 
public static final String JSON_MESSAGE = "message"; 
public static final String JSON_RESPONSE = "response"; 

private static final Logger logger = Logger.getLogger(WebServer.class 
     .getName()); 

private static final String FAVICON_URL = "/favicon.ico"; 
private static final String MYME_JSON = "application/json"; 
private static final int PORT = 1313; 

public WebServer() throws IOException { 
    super(PORT); 
} 

@Override 
public Response serve(IHTTPSession session) { 
    Map<String, String> params = session.getParms(); 
    String uri = session.getUri(); 
    if (!uri.equals(FAVICON_URL)) { 
     logger.info("Request url: " + uri); 
    } 
    JSONObject result = RoutesController.resolveRoute(uri, params); 
    Response response = new Response(Status.OK, MYME_JSON, 
      result.toString()); 
    return response; 
} 
} 

代码:

public class Application { 

private static final Logger logger = Logger.getLogger(Application.class 
     .getName()); 

public static void main(String[] args) { 
    ServerRunner.run(WebServer.class); 
    return; 
} 
} 

将是任何信息非常有帮助...

回答

1

终于搞清楚是什么问题了。默认ServerRunner NanoHTTPD使用System.in.read();等待输入时会按下停止服务器。问题是System.in.read();阻止应用去背景。所以我只写了我自己的ServerRunner,它不会与inputstream交互,服务器可以通过简单的bash脚本或获取请求来停止。

0

我有感觉这是因为你的主线程在服务器能够绑定到appropri之前退出吃了港口。要验证这一点,请使用this作为指导,添加一小段(10秒钟)sleep。这应该买足够的时间bind做需要的。

+0

感谢您的回答,但不幸的是sleep()没有帮助,行为也一样。 –