开发者

Detecting whether EOF is at the beginning or somewhere in the middle in readInt

I'm using the following to read a packet of data from a DataInputStream (wrapped around a socket).

    DataInputStream ins = ....;
    boolean cleanBreak = true;

    try {

        synchronized (readLock) {

            // read: message length
            int ml = ins.readInt();
   开发者_开发技巧         cleanBreak = false;

            // read: message data
            byte[] msg = IO.readBytes(ins, ml);

        }

    } catch (IOException e) {


            final boolean eof = e instanceof EOFException && cleanBreak;

        ...

Using the cleanBreak boolean, I want to determine whether an EOF occurs in the middle of a packet (abruptly) or nicely between two packets. Currently this works when the EOF is in the data part, but not if it's in the header (the int), e.g. if only 2 more bytes are left when reading the header.

How can I do that?


One way would be to inline readInt:

public final int readInt() throws IOException {
    int ch1 = in.read();
    int ch2 = in.read();
    int ch3 = in.read();
    int ch4 = in.read();
    if ((ch1 | ch2 | ch3 | ch4) < 0)
        throw new EOFException();
    return ((ch1 << 24) + (ch2 << 16) + (ch3 << 8) + (ch4 << 0));
}

And adapt it with a special check for the first byte.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜