HTTP Server System.out problem
So I have an assignment where I have to make a HTTP Server with chosen programming language. No big deal. I have encountered a p开发者_如何学Croblem that I cant seem to figure out. Every time I load the homepage that and the server response, it prints out about 5 times. Cant figure out why. Okay so what I mean:
Code Snippets:
while(true){
connectedClient = listenSocket.accept();
inFromClient = new BufferedReader( new InputStreamReader( connectedClient.getInputStream()));
outToClient = new DataOutputStream(connectedClient.getOutputStream());
String requestString = inFromClient.readLine();
String headerLine = requestString;
StringTokenizer tokenizer = new StringTokenizer(headerLine);
String httpMethod = tokenizer.nextToken();
String httpQueryString = tokenizer.nextToken();
requestString = inFromClient.readLine();
if (httpMethod.equals("GET")) {
if (httpQueryString.equals("/Home")) {
// The default home page status code 200
dateHeader();
connectionCloseHeader();
}
//other code not related
}
And this is my date header method:
public static void dateHeader() throws Exception{
DateFormat dateFormat = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss z");
Date date = new Date();
System.out.println("Date: " + dateFormat.format(date));
}
My output to the terminal will be 5 printouts of the date. I made sure that the connection and such was closed but same thing happens. Anyone have an idea why this is happening? Thanks.
EDIT
Seems that when using Chrome I get the one print out no problem. I was testing with Opera and that was giving me the 5 printouts. Perhaps something with the way the browsers work is causing the issue. Ill just use chrome now for it though.
I can't account for five different invocations right off, but if you're using a typical browser to hit this HTTP server, you'll immediately see two requests: one for the resource itself and one for a favicon.ico. Somewhere in your request handler, you should read in and print out the entire request. Then you can see exactly what all the requests are for.
精彩评论