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

熱點內容
雲伺服器的ip固定的嗎 發布:2025-07-15 19:26:12 瀏覽:934
怎麼建立電腦配置文件 發布:2025-07-15 19:23:57 瀏覽:672
手機導航源碼下載 發布:2025-07-15 19:18:29 瀏覽:499
什麼是原生態安卓機 發布:2025-07-15 19:16:52 瀏覽:686
linux的安裝目錄在哪 發布:2025-07-15 19:10:04 瀏覽:724
2008編程入門經典 發布:2025-07-15 18:58:44 瀏覽:603
艾派密碼是什麼 發布:2025-07-15 18:47:40 瀏覽:588
密碼鎖如何在裡面開門 發布:2025-07-15 18:35:00 瀏覽:521
額溫演算法 發布:2025-07-15 18:18:14 瀏覽:728
ie客戶端事件腳本執行異常 發布:2025-07-15 18:10:13 瀏覽:26