【问题标题】:Can't run jar with built in nanohttpd server in background (with nohup)无法在后台运行带有内置 nanohttpd 服务器的 jar(使用 nohup)
【发布时间】:2015-06-27 20:07:11
【问题描述】:

我的应用程序中有简单的 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 &)。

我的服务器类的代码:

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

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

【问题讨论】:

    标签: java jar nohup nanohttpd


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

      • 感谢您的回答,但不幸的是 sleep() 没有帮助,行为保持不变。
      猜你喜欢
      • 1970-01-01
      • 2022-07-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-27
      • 2020-03-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多