关于tio 协议(Packet)中 消息头的长度(HEADER_LENGTH)的理解

原创
2018/12/24 17:05
阅读数 446

用了t-io很长时间了,但是没有深层次的 阅读代码,写本篇博客为了记录下 对 tio  协议(Packet)中 消息头的长度(HEADER_LENGTH)的理解

import java.nio.ByteBuffer;
import java.nio.ByteOrder;

import org.nutz.log.Log;
import org.nutz.log.Logs;

public class ByteBufferTest {
	
    private static final Log log = Logs.get();
	private final static byte MSG_TYPE = 8;
	
	public static void main(String[] args) throws Exception{
		
		/**
		 * 消息头的长度 1+4  
		 * 所谓 1 是 协议定义的消息类型 例如 byte MSG_TYPE = 8; 占一个字节
		 * 所谓 4 是 消息体的长度  int类型 占4个字节
		 */
		int headerLen = 5;
		
		String body = "hello tio";
		int bodyLen = body.length();//消息体长度
		
		int allLen = headerLen + bodyLen;

		ByteBuffer buffer = null;
		buffer = ByteBuffer.allocate(allLen);	
		buffer.order(ByteOrder.BIG_ENDIAN);
		
		buffer.put(ByteBufferTest.MSG_TYPE);
		log.infof("[encode1]-limit=%s,position=%s", buffer.limit(),buffer.position());

		buffer.putInt(bodyLen);
		log.infof("[encode2]-limit=%s,position=%s", buffer.limit(),buffer.position());
		
		buffer.put(new String(body).getBytes("UTF-8"));
		log.infof("[encode3]-limit=%s,position=%s", buffer.limit(),buffer.position());

		
		buffer.position(0);
		
		byte type = buffer.get();//消息类型
		System.out.println("消息类型:" + type);
		
		int bodyLength = buffer.getInt();//消息体长度
		System.out.println("消息体长度:" + bodyLength);
		
		byte[] dst = new byte[bodyLength];//消息内容
		buffer.get(dst);
		System.out.println("消息内容:" + new String(dst));
	}
	
	/**
	 * int 转byte
	 * int 类型 占4个字节
	 * @param val
	 * @return
	 */
	public static byte[] intToByte(int val){
		byte[] b = new byte[4];
		b[0] = (byte)(val & 0xff);
		b[1] = (byte)((val >> 8) & 0xff);
		b[2] = (byte)((val >> 16) & 0xff);
		b[3] = (byte)((val >> 24) & 0xff);
		return b;
		
	}
}

 

展开阅读全文
加载中
点击加入讨论🔥(1) 发布并加入讨论🔥
1 评论
0 收藏
0
分享
返回顶部
顶部