java服务器http服务器接收来自Chrome的空请求

时间:2013-01-04 22:49:25

标签: java http sockets

当从Chrome向localhost发送请求时,程序会收到两个请求:一个(可能是两个)为空,一个请求正常。
当我对Firefox做同样的事情时,我有时会得到一个空的HTTP请求,其他的都没问题 我认为它与favicon有关,我不确定为什么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;
        }
    }

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

-----------------------------------------

1 个答案:

答案 0 :(得分:1)

available()不是流结束的有效测试。见Javadoc。你应该逐行阅读所有的标题,直到你得到一个空行。