Hey guys,
I have just finished my first of three years in an informatics apprenticeship and I thought it would be a good idea to do something during the holidays to improve my Java and Networking skills. Thats why I started to read a book about Java Servers and Servlets, but unfortunately I'm already having some trouble. Right in the beginning of the book, there is a programme, in which a self created HTTP-Server should respond to a GET-request and it just doesnt want to work for me as it should.
When I'm starting the programme and enter http://localhost:8080/index.html (they say you should create an index.html somewhere in your workspace, so the server has something to respond) the only output that I get in my eclipse is:
"Request: GET / HTTP/1.1
404 Not Found"
Ok. So the server is at least getting the request, which can be seen in the first line "Request: GET / HTTP/1.1". But I have really no idea what I should do, to make the server respond to the request by showing the index.html, which is how its meant to work.
I'm still a newbie with all that stuff so I hope there are some nice guys out there who can share some of their experience with me, cause I'm really not finding an answer for that problem by myself.
Btw here's the code for that programme:
Thanks already for all your efforts!package httpServer;
import java.io.*;
import java.net.*;
import java.util.StringTokenizer;
public class OneShotHttpd{
public final static int HTTP_PORT = 8080;
public static void main(String[] args){
try{
ServerSocket listen = new ServerSocket(HTTP_PORT);
Socket client = listen.accept();
BufferedReader is = new BufferedReader(new InputStreamReader(client.getInputStream()));
DataOutputStream os = new DataOutputStream(client.getOutputStream());
String request = is.readLine();
System.out.println("Request: " + request);
StringTokenizer st = new StringTokenizer(request);
if((st.countTokens()==3) && st.nextToken().equals("GET")){
request = st.nextToken().substring(1);
if(request.endsWith("/") || request.equals(""))
request += "index.html";
sendDocument(os, request);
}
else
System.err.println("400 Bad Request");
is.close();
os.close();
client.close();
}
catch(IOException ioe){
System.err.println("Fehler: " + ioe.toString());
}
}
public static void sendDocument(DataOutputStream out, String file) throws IOException{
try{
BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));
byte[] buf = new byte[1024];
int len;
while((len = in.read(buf, 0, 1024)) != -1){
out.write(buf, 0, len);
}
in.close();
}
catch(FileNotFoundException fnfe){
System.err.println("404 Not Found");
}
}
}