Java Socket关于消息边界的问题解决(二)

2014-11-24 07:53:48 · 作者: · 浏览: 2
} } }

好了!自己运行一下吧!

这个例子还有一个缺点,就是只考虑了“定界符”是单字节的情况,对于多字节的情况没有考虑。自己也没有找到什么好的办法,如果大家有知道的请回复一下。

对了,对于那个处理定界符的消息类,还可以写成这样:

public class LengthFramer
{

    public static final int MAXMESSAGELENGTH = 65535;

    public static final int BYTEMASK = 0xff;

    public static final int SHORTMASK = 0xffff;

    public static final int BYTESHTFT = 8;

    public void frameMsg(byte[] message, OutputStream output)
            throws IOException
    {
        if (message.length > MAXMESSAGELENGTH)
        {
            throw new IOException("message to long");
        }

        output.write((message.length >> BYTESHTFT) & BYTEMASK);
        output.write(message.length & BYTEMASK);

        output.write(message);
        output.flush();
    }

    public byte[] nextMsg(InputStream input) throws IOException
    {
        int length;
        DataInputStream dataInput;
        try
        {
            dataInput = new DataInputStream(input);
            length = dataInput.readUnsignedShort();
        }
        catch (EOFException e)
        {
            return null;
        }
        byte[] msg = new byte[length];
        dataInput.readFully(msg);
        return msg;
    }
}
上边的这个写法,感觉怪怪的,但是运行结果是对的。