---
title: "tcp解包"
author: "hzp"
date: "2015-06-10T09:12:00Z"
tags: []
categories: ["编程语言"]
slug: "tcp"
draft: false
lastmod: "2015-06-09T14:07:01Z"
id: 2218076
url: "https://hzp.iteye.com/blog/2218076"
---

包格式： 包头(数据体长度) + 数据体

 

```
/**
	 * 解数据包体
	 * @param is
	 * @return
	 * @throws IOException 
	 */
	public String getDataBody(InputStream is) throws IOException {
		String dataBody = null;
		// 获取头部
		byte[] head = getData(is, 4);
		int dataLength = ByteUtil.toInt(head);

		// 获取数据
		byte[] data = getData(is, dataLength);
		dataBody = GZipUtil.uncompressToString(data);

		return dataBody;
	}
	
	/**
	 * 拆包
	 * @param is
	 * @param length
	 * @return
	 * @throws IOException
	 */
	private byte[] getData(InputStream is, int length) throws IOException {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		byte[] buffer = new byte[5120];
		int nIdx = 0; //累计读取了多少位
		int nReadLen = 0; //一次读取了多少位

		while (nIdx < length) { //循环读取足够长度的数据
			
			if(length - nIdx >= buffer.length){ //剩余数据大于缓存，则全部读取
				nReadLen = is.read(buffer);
			}else{ //剩余数据小于缓存，则注意拆分其他包，只取当前包剩余数据
				nReadLen = is.read(buffer, 0, length - nIdx);
			}
			
			if (nReadLen > 0) {
				baos.write(buffer, 0, nReadLen);
				nIdx = nIdx + nReadLen;
			} else {
				break;
			}
			
		}
		
		return baos.toByteArray();
	}
```