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.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 OutputStream());dis = new InputStream());} catch (Exception e) {// TODO: handle exceptione.printStackTrace();}}public void writeMsg(String msg, int type) {byte[] MsgB = Bytes(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.lenint i = 0;// 写入类型bb.asIntBuffer().put(type);for (i = 0; i < by.length; i++) {SendMsg[i] = by[i];}bb.asIntBuffer().put(0);// 清空// 写入长度bb.asIntBu
本文发布于:2024-01-31 03:31:19,感谢您对本站的认可!
本文链接:https://www.4u4v.net/it/170664308025060.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
留言与评论(共有 0 条评论) |