当前位置:首页 » 编程语言 » java粘包

java粘包

发布时间: 2023-05-18 00:24:37

java 解析二进制 粘包 半包问题 求详细代码 万分感谢

try
{
InputStream is = socket.getInputStream();
while(running)
{
/*
* 读取消息长度
*/
byte[] totalLen = new byte[4];
int readLen = 0;//本次读取的字节数
int position = 0;//已经读取数据的下一个位置
while((readLen=is.read(totalLen,position,(4-position)))>=0)
{
position = position + readLen;
if(position==4)
{
break;
}
}
if(readLen<0)
{//读取到EOF,socket已close或reset
throw new SocketException("读取数据流结尾.");
}

int length = SGIP.byteArrayToInt(totalLen);
ByteBuffer mesg = ByteBuffer.allocate(length);
mesg.order(SGIP.getByteOrder());
mesg.put(totalLen);

//读取所有消息
readLen = 0;
position = mesg.position();
while((readLen=is.read(mesg.array(), position, mesg.remaining()))>=0)
{
position = position + readLen;
mesg.position(position);
if(mesg.remaining()==0)
{
break;
}
}
if(readLen<0)
{//读取到EOF,socket已close或reset
throw new SocketException("读取数据流结尾.");
}
mesg.position(0);

//解析消息
mesg.order(ByteOrder.BIG_ENDIAN);

try
{
//解析mesg
}
catch (Exception e)
{
logger.error("语法错误出错,无法解析",e);
//接收到非法命令,断开连接
socket.close();
break;
}

logger.debug(this.getName()+"退出");

热点内容
安卓手机设备在哪里找 发布:2025-07-16 02:49:28 浏览:356
php建立数组 发布:2025-07-16 02:34:30 浏览:284
oracle存储过程同步 发布:2025-07-16 02:29:18 浏览:941
欧诺s买哪个配置的好 发布:2025-07-16 02:26:22 浏览:559
热点可以建立ftp吗 发布:2025-07-16 02:26:21 浏览:304
如何选择最佳配置 发布:2025-07-16 01:56:44 浏览:604
mad加密 发布:2025-07-16 01:52:12 浏览:425
linux64位内存 发布:2025-07-16 01:02:36 浏览:960
压缩衣尺码表 发布:2025-07-16 00:47:33 浏览:640
安卓恢复了出厂怎么找回照片 发布:2025-07-16 00:43:56 浏览:933