java objectinputstream中的readObject如何知道要读取多少字节?

2024-10-03 04:32:00 发布

您现在位置:Python中文网/ 问答频道 /正文

在socket I/O中,我可以知道objectinputstreamreadObject如何知道要读取多少字节?内容长度是封装在字节本身内,还是只是读取缓冲区中所有可用的字节?在

我问这个是因为我指的是Python套接字how-to,它说

Now if you think about that a bit, you’ll come to realize a fundamental truth of sockets: messages must either be fixed length (yuck), or be delimited (shrug), or indicate how long they are (much better), or end by shutting down the connection. The choice is entirely yours, (but some ways are righter than others).

然而在另一篇文章中,@DavidCrawshaw提到

So readObject() does not know how much data it will read, so it does not know how many objects are available.

我很想知道它是怎么工作的。。。在


Tags: ortoyou内容字节notitsocket
2条回答

你对你所引用的答案解释过度了。readObject()不知道它将提前读取多少字节,但一旦它开始读取,它就只是根据一个协议解析输入流,该协议由标记、原语值和对象组成,而后者又由标记、原语值和其他对象组成。它不需要提前知道。考虑XML的类似ish情况。您不知道文档将提前多长时间,或者每个元素,但是您知道什么时候您已经读完了,因为协议告诉您。在

readOject()方法正在使用BlockedInputStream读取字节。如果检查ObjectInputStreamreadObject,它正在调用

readObject0(false).

private Object readObject0(boolean unshared) throws IOException {
    boolean oldMode = bin.getBlockDataMode();
    if (oldMode) {
        int remain = bin.currentBlockRemaining();
        if (remain > 0) {
        throw new OptionalDataException(remain);
        } else if (defaultDataEnd) {
        /*
         * Fix for 4360508: stream is currently at the end of a field
         * value block written via default serialization; since there
         * is no terminating TC_ENDBLOCKDATA tag, simulate
         * end-of-custom-data behavior explicitly.
         */
        throw new OptionalDataException(true);
        }
        bin.setBlockDataMode(false);
    }

    byte tc;
    while ((tc = bin.peekByte()) == TC_RESET) {
        bin.readByte();
        handleReset();
    }

从流中读取的是使用bin.readByte().bin is BlockiedDataInputStream,后者反过来使用PeekInputStream来读取它。这个类最终正在使用输入流.read(). 根据read方法的描述:

^{pr2}$

所以基本上它读取一个又一个字节,直到遇到-1。所以正如ejb提到的,它永远不会提前知道有多少字节需要读取。希望这能帮助你理解它。在

相关问题 更多 >