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 ...
source to share
ServerRunner
for NanoHTTPD use
System.in.read();
to wait for a button to be pressed to stop the server. The problem is that
System.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.
source to share