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

795 views Asked by At

I have simple nanohttpd server implementation inside my application and it works fine when I am running it in regular way (java -jar myApp.jar). But when I am trying to run it as background process nanohttpd doesn't get http requests, browser just stucks and never receives response. There is also no messages in log file, I am geting only message that server started: Server started, Hit Enter to stop.

The command I use to run my application in background: nohup java -jar myApp.jar & I also tried lots of different variations with writing in log and etc (i.e nohup java -jar myApp.jar >myApp.log 2>&1 &).

Code of my server 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;
}
}

Code of my main 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;
}
}

Will be very helpful for any information...

2

There are 2 answers

0
Alon Zilberman On BEST ANSWER

Finally figured out what was the problem. Default ServerRunner of NanoHTTPD use System.in.read(); for waiting when enter will be pressed to stop the server. The problem is that System.in.read(); prevents the application of go background. So I just wrote my own ServerRunner which doesn't interact with inputstream, and server can be stopped either by simple bash script or get request.

1
DoubleA On

I have a feeling that this is because your main thread is exiting before the server is able to bind to the appropriate port. To verify this, add a short (10 seconds) sleep using this as a guide. This should buy enough time for bind to do what's needed.