代码之家  ›  专栏  ›  技术社区  ›  Mikepote

Javasun.net.HttpServer写入OutputStream引发IOException“主机中的软件中止了已建立的连接”

  •  0
  • Mikepote  · 技术社区  · 7 年前

    我有一个HttpServer,它在我的handle()函数中使用以下代码为文件提供服务。

    从本地磁盘100%正确读取文件,并且正确填充了bytes[]数组。一旦我尝试将这些字节写入OutputStream os ,我得到一个“IOException-已建立的连接被主机中的软件中止”错误。

    最糟糕的是代码正在工作——我在客户端接收这些字节,从客户端的角度来看,一切都在100%地工作。除了默默地忽略这个错误之外,我还有什么需要检查的吗?

    @Override
    public void handle(HttpExchange t) throws IOException
    {
    
        //I heard it was a good idea to consume the input stream fully:
        InputStream is = t.getRequestBody();
        while (is.read() != -1) {
            is.skip(0x10000);
        }
        is.close();
    
        String path = t.getRequestURI().getPath();
        String method = t.getRequestMethod();
    
        if (! ("HEAD".equals(method) || "GET".equals(method)))
        {
            sendError(t, 400, "Invalid method");
            return;
        }
    
        ... snipped some path validation and error checking ...
    
        try
        {
            Headers h = t.getResponseHeaders();
            h.set("Content-Type", "text/html");
            h.set("Access-Control-Allow-Methods", "GET");
            h.set("Access-Control-Allow-Headers", "Authorization, Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since");
            h.set("Access-Control-Allow-Origin", "*");
            h.set("Timing-Allow-Origin", "*");
            //Set aggressive caching:
            h.set("Cache-Control", "public, max-age=31536000");
    
            File f = new File(baseDirectory + path).getCanonicalFile();
    
            if (!f.exists() || !f.isFile())
            {
                sendError(t, 404, "Not found");
                return;
            }
    
            byte[] bytes = Files.readAllBytes(Paths.get(f.getPath()));
    
            t.sendResponseHeaders(200, bytes.length);
    
            OutputStream os = t.getResponseBody();
    
            //ERROR HAPPENS HERE:
            os.write(bytes);
            os.close();
    
        }
        catch (Exception e)
        {   
            Main.log("HTTP: Error trying to read file "+path+": "+ e.toString());
        }
    
    
        t.close();
    }
    
    1 回复  |  直到 7 年前
        1
  •  0
  •   clausr    7 年前

    我打赌你用的是chrome,

    如果chrome对连接速度不满意,它将发送另一个GET请求并取消最慢的一个请求,这将导致“已建立的连接被中止…”异常。

    因此,在仍然检索完整文件时,日志中会出现错误。

    推荐文章