I'm trying to make a Java HTTP server to learn how to use Java sockets and I'm having a bit of an issue. The browser doesn't seem to receive any data! The issue seems to be in the println method sending the HTTP header, as everything else works fine so far.
Code:
class HTTPServerSession extends Thread {
private Socket socket_ = null;
public HTTPServerSession(Socket socket) {
//Check the provided socket is not null
if (socket == null) {
throw new NullPointerException();
}
//Set socket variable
socket_ = socket;
}
public void start() {
try {
//Create socket reader
BufferedReader reader = new BufferedReader(new InputStreamReader(socket_.getInputStream()));
//Create array of requests
ArrayList<String> requests = new ArrayList<String>();
//Start reading HTTP request
while (true) {
//Read request line
String s = reader.readLine();
//Print request
System.out.println(s);
//Add request line
if (s.equals("")) {
break;
} else {
requests.add(s);
}
}
//Get file name
String file = null;
for (int i = 0; i < requests.size(); i++) {
//Split line
String request[] = requests.get(i).split(" ");
//Get filename
if (request[0].equals("GET")) {
file = request[1];
i = requests.size();
System.out.println(file);
}
}
//Send request
BufferedOutputStream writer = new BufferedOutputStream(socket_.getOutputStream());
println(writer, "HTTP/1.1 200 OK");
println(writer, "Content-Type: text/html");
println(writer, "Content-Length: 18");
println(writer, "");
println(writer, "<p>Hello World</p>");
//Try close the socket
System.out.println("Socket closing");
socket_.close();
System.out.println("Socket closed");
} catch (Exception e) {
//Print error
System.out.println(e);
System.out.println(e.getStackTrace());
}
}
private void println(BufferedOutputStream bos, String s)
throws IOException {
String news = s + "\r\n";
byte[] array = news.getBytes();
for (int i = 0; i < array.length; i++) {
bos.write(array[i]);
}
return;
}
}