不能 运行 jar 在后台使用内置的 nanohttpd 服务器(使用 nohup)

Can't run jar with built in nanohttpd server in background (with nohup)

我的应用程序中有简单的 nanohttpd 服务器实现,当我以常规方式 运行 连接它时它工作正常 (java -jar myApp.jar)。但是当我尝试 运行 它作为后台进程 nanohttpd 没有收到 http 请求时,浏览器只是卡住并且永远不会收到响应。日志文件中也没有消息,我只收到服务器启动的消息:Server started, Hit Enter to stop.

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

我的服务器代码class:

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;
}
}

我的主要代码class:

public class Application {

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

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

对任何信息都非常有帮助...

我感觉这是因为您的主线程在服务器能够绑定到适当的端口之前退出。要验证这一点,请使用 this 作为指南添加一个简短的(10 秒)sleep。这应该为 bind 争取足够的时间来完成所需的工作。

终于知道问题出在哪里了。 NanoHTTPD 的默认 ServerRunner 使用 System.in.read(); 等待按下回车键停止服务器。问题是System.in.read();阻止了go后台的应用。所以我只是写了我自己的 ServerRunner,它不与输入流交互,服务器可以通过简单的 bash 脚本或获取请求停止。