當前位置:首頁 » 編程語言 » 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()+"退出");

熱點內容
java返回this 發布:2025-10-20 08:28:16 瀏覽:712
製作腳本網站 發布:2025-10-20 08:17:34 瀏覽:974
python中的init方法 發布:2025-10-20 08:17:33 瀏覽:686
圖案密碼什麼意思 發布:2025-10-20 08:16:56 瀏覽:837
怎麼清理微信視頻緩存 發布:2025-10-20 08:12:37 瀏覽:744
c語言編譯器怎麼看執行過程 發布:2025-10-20 08:00:32 瀏覽:1085
郵箱如何填寫發信伺服器 發布:2025-10-20 07:45:27 瀏覽:314
shell腳本入門案例 發布:2025-10-20 07:44:45 瀏覽:194
怎麼上傳照片瀏覽上傳 發布:2025-10-20 07:44:03 瀏覽:882
python股票數據獲取 發布:2025-10-20 07:39:44 瀏覽:840