好了!自己运行一下吧!
对了,对于那个处理定界符的消息类,还可以写成这样:
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;
}
}
上边的这个写法,感觉怪怪的,但是运行结果是对的。