java粘包
㈠ 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()+"退出");