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()+"退出");