TL;DR
I've followed this tutorial to create a webserver in java.
However, the following part always fails and as result, the whole web server crashes or hangs up on this while loop:
BufferedReader br = new BufferedReader(new InputStreamReader(client.getInputStream()));
StringBuilder requestBuilder = new StringBuilder();
String line;
while (!(line = br.readLine()).isEmpty()) {
requestBuilder.append(line + "\r\n");
}
Sometimes it throws a NullPointerException at the while loop line. Sometimes it just hangs up or crashes. Sometimes it takes ages to do anything and sometimes it works. I also tried checking if the line
String is null
or if it == ""
but this also lets the server crash.
A little more info:
This code is running on JDK 1.8 as a plugin in a Minecraft server on a separate thread (Runnable).
I don't know what I should do anymore.
I've tried so much and it just doesn't work.
I hope someone could help me.
Best regards,
Max
EDIT:
My current state of "testing the loop" is the following:
String line = br.readLine();
while(line != null) {
if(line.isEmpty()) {
line = null;
} else {
requestBuilder.append(line);
line = br.readLine();
}
}
It works and loads the website.
But after this, it just crashes.
I've put in a logger in the guessContentType()
function (you can see it in the tutorial I've referred to at the beginning of this question).
It looks like the browser is requesting the index.html file and after it gets it from the server it requests all CSS and js (assets) files that were imported. At this point, the server still runs but round about 3 seconds after it loaded all assets something is requesting the index.html file again and then it crashes.
EDIT 2:
Another thing to mention.
I just tried making a get request via postman.
It turns out when making a GET request over postman and not the browser it gives back an ECONNRESET error in postman and I can see the index.html
file that killed the server as described in the first edit.