TLV: type length value,用来处理tcp粘包的一种解决办法。在发送tcp包时,用type标明数据类型,length标明数据长度,value代表要发送的数据。
type、length:一般用2到4个字节表示。
-----type(4bytes)------|--------length(4bytes)--------|-------value------
//tcp数据写入、读取处理
package net;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.charset.StandardCharsets;
public class Tlv {
DataInputStream dis = null;
DataOutputStream dos = null;
Socket s = null;
public Tlv(Socket s) {
this.s = s;
try {
dos = new DataOutputStream(s.getOutputStream());
dis = new DataInputStream(s.getInputStream());
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
public void writeMsg(String msg, int type) {
byte[] MsgB = msg.getBytes(StandardCharsets.UTF_8);
int len = MsgB.length;
//
byte[] by = new byte[4];
ByteBuffer bb = ByteBuffer.wrap(by);
bb.order(ByteOrder.LITTLE_ENDIAN);// 这里使用小端序
byte[] SendMsg = new byte[4 + 4 + len]; // int(type) + int(len) + msg.len
int i = 0;
// 写入类型
bb.asIntBuffer().put(type);
for (i = 0; i < by.length; i++) {
SendMsg[i] = by[i];
}
bb.asIntBuffer().put(0);// 清空
// 写入长度
bb.asIntBu