When sending requests to the localhost from Chrome the program receives two requests: one(maybe two) empty and one with a normal HTTP request.
When I do the same with Firefox I sometimes get a single empty HTTP request, the others are fine.
I think it has something to do with favicon, I’m not sure why there isn’t anything in the outputStream
ServerSocket server=null;
Socket socket;
try
{ server=new ServerSocket(80);
while(true)
{ try
{ socket = server.accept();
Worker worker=new Worker(socket);
(new Thread(worker)).start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
....
//Worker.java
public class Worker implements Runnable
{ private Socket socket;
public void run()
{ try
{ InputStream inStream = new BufferedInputStream(
socket.getInputStream());
byte[] array = new byte[1000];
ByteArrayOutputStream outputStream = new ByteArrayOutputStream( );
while(inStream.available()>0)
{ outputStream.write(array);
}
System.out.println("-----------------------------------------");
System.out.println(outputStream);
System.out.println("-----------------------------------------");
}
catch (IOException e)
{ e.printStackTrace();
}
try
{ socket.close();
}
catch (IOException e)
{ e.printStackTrace();
}
}
public Worker(Socket socket)
{ this.socket=socket;
}
}
Sample request from Chrome:
-----------------------------------------
-----------------------------------------
-----------------------------------------
-----------------------------------------
-----------------------------------------
GET / HTTP/1.1
Host: localhost
Connection: keep-alive
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.97 Safari/537.11
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3
-----------------------------------------
available() isn’t a valid test for end of stream. See the Javadoc. You should read all the headers line by line until you get a blank line.