java 解析二进制 粘包 半包问题 求详细代码 万分感谢
- 你的回答被采纳后将获得:
- 系统奖励15(财富值+成长值)+难题奖励10(财富值+成长值)+提问者悬赏30(财富值+成长值)
1个回答
展开全部
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()+"退出");
{
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()+"退出");
本回答被提问者和网友采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询