0

I have a HttpServer which is serving files using the following code inside my Handler's handle() function.

The file is read 100% fine from the local disk and the bytes[] array is filled correctly. As soon as I try to write those bytes to the OutputStream os, I get an "IOException - An established connection was aborted by the software in your host machine" error.

The hell of it is that the code is WORKING - I'm recieving those bytes on the client side and from the client's point of view, everything is working 100%. Apart from silently ignoring this error is there anything else I should check?

@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();
}
Mikepote
  • 6,042
  • 3
  • 34
  • 38

1 Answers1

0

I bet you are using chrome,

If chrome is not satisfied with the connection speed, it sends another GET request and cancels the slowest one which results in "An established connection was aborted..." exception.

hence the error in the log while still retrieving a complete file.

clausr
  • 21
  • 1