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

用了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;
		
	}
}

 

转载于:https://my.oschina.net/longtutengfei/blog/2992607

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值