`

tcp解包

 
阅读更多

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

 

/**
	 * 解数据包体
	 * @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();
	}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics