Java sun.net.HttpServer写入OutputStream会抛出IOException“已建立的连接已被主机中的软件中止”

问题描述 投票:0回答:1

我有一个HttpServer,它在我的Handler的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();
}
java http httpserver sun
1个回答
0
投票

我打赌你用的是铬,

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

因此,仍然检索完整文件时日志中的错误。

© www.soinside.com 2019 - 2024. All rights reserved.