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...
Finally figured out what was the problem. Default
ServerRunner
of NanoHTTPD useSystem.in.read();
for waiting when enter will be pressed to stop the server. The problem is thatSystem.in.read();
prevents the application of go background. So I just wrote my ownServerRunner
which doesn't interact with inputstream, and server can be stopped either by simple bash script or get request.