Can't start jar with embedded nanohttpd server in background (no nohup)

I have a simple nanohttpd implementation in my application and it works fine when I run it normally ( java -jar myApp.jar

). But when I try to run it as a background process, nanohttpd doesn't receive HTTP requests, the browser just hangs on and never gets a response. There are no messages in the log file either, I only get a server start message:Server started, Hit Enter to stop.

The command I use to run my app in the background: nohup java -jar myApp.jar &

I have also tried many different options for logging, etc. (ie nohup java -jar myApp.jar >myApp.log 2>&1 &

).

My server class code:

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

      

My main class code:

public class Application {

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

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

      

Will be very helpful for any information ...

+3


source to share


2 answers


Finally, it figured out what the problem was. By default ServerRunner

for NanoHTTPD useSystem.in.read();



to wait for a button to be pressed to stop the server. The problem is thatSystem.in.read();



prevents the go background from being applied. So I just wrote my own ServerRunner

one that doesn't interact with the input stream and the server can be stopped either with a simple bash script or get a request.
+1


source


I have a feeling this is because your main thread exits before the server can bind to the appropriate port. To test this, add a short one (10 seconds) sleep

with this as a guide. This should buy enough time bind

to do the right thing.



0


source







All Articles