0

我正在尝试编写一个简单的 HTTP 异步服务器和一个测试客户端。我的测试客户端向服务器发出了一堆请求,但除了读取它之外对响应没有做任何事情。我遇到的问题是在一堆成功的响应之后,我的客户端无法读取特定请求的完整响应。我不知道为什么会这样。

这是我的服务器的读/写处理程序: 读/写处理程序

重要的代码是发送文件的函数:

    public void handleWrite(SelectionKey key) throws IOException {
    client.write(out); // Write the headers to the stream
    if (state == State.SENDING_RESPONSE && out.remaining() == 0) {
        // We are done writing the headers
        if (sendFile && (mapped == null)) {
            // Send the file via direct transfer
            System.err.println("DT: " + fPath + " " + pos + "/" + fileSize);
            long transferred = f.transferTo(pos, fileSize, client);
            pos += transferred;
            System.err.println("DT: " + fPath + " " + pos + "/" + fileSize);
        } else if (mapped != null){
            // Send the file (in mapped from either filesystem or from
            // cache)
            System.err.println("MAPPED: " + fPath + " " + mapped.position() + "/" + mapped.limit());
            written += client.write(mapped);
            System.err.println("MAPPED: " + fPath + " " + written + "/" + mapped.limit());
        }
    }
    if (out.remaining() == 0
            && ((mapped == null && pos == fileSize) || (mapped != null && mapped
                    .remaining() == 0))) {
        // We are done transferring the file!
        System.err.println(pos + " " + fileSize);
        assert (pos == fileSize) || (mapped.position() == mapped.limit()) : "File not sent.";
        // Must reset position if from cache
        if (inCache) {
            mapped.position(0);
        }
        if (sendFile) {
            cache();
            f.close();
            inputStream.close();
        }
        state = State.SOCKET_CLOSED;
        d.getKey(client).cancel();
        client.close();
    }
}

这是客户端中的响应处理程序: 响应处理程序

重要的代码是阅读部分:

        if((sz = header.get("content-length")) != null) {
        bodySize = Integer.parseInt(sz);
        byte[] buff = new byte[bodySize];
        int k = 0, read = 0;
        while((k = connection.getInputStream().read(buff, read, bodySize - read)) != -1 && read < bodySize) {
            read += k;
        }
        assert read == bodySize : "Not all of file read. " + read + " " + bodySize;
    }

响应处理程序底部的断言是失败的断言。我还包括了服务器和调度程序本身,以及客户端(如果有帮助的话)。 服务器/调度 程序客户端

4

1 回答 1

0
while((k = connection.getInputStream().read(buff, read, bodySize - read)) != -1 && read < bodySize) {
      read += k;

扔掉它并使用DataInputStream.readFully(data).

于 2013-10-18T05:55:20.587 回答