62,621
社区成员
发帖
与我相关
我的任务
分享
**
* TCP套接字使用“显示长度”的方式处理消息边界
*
* @author dabing
*
*/
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 BYTESHIFT = 8;
private DataInputStream in;
public LengthFramer(InputStream in) {
this.in = new DataInputStream(in);
}
public void sendMsg(byte[] message, OutputStream out) throws IOException {
if (message.length > BYTESHIFT) {
throw new IOException("message too long");
}
out.write((message.length >> BYTEMASK) & BYTEMASK);
out.write(message.length & BYTEMASK);
out.write(message);
out.flush();
}
public byte[] receiveMsg() throws IOException {
int length;
try {
length = in.readUnsignedShort();
} catch (EOFException e) {
return null;
}
byte[] msg = new byte[length];
in.readFully(msg);
return msg;
}
}



