0

当从 Chrome 向 localhost 发送请求时,程序会收到两个请求:一个(可能是两个)空请求和一个带有普通 HTTP 请求的请求。
当我对 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

-----------------------------------------
4

1 回答 1

1

available() 不是流结束的有效测试。请参阅 Javadoc。您应该逐行阅读所有标题,直到出现空行。

于 2013-01-04T22:59:24.843 回答