簡體   English   中英

讀取Socket流數據並讀取前2個字節,查找其余消息長度

[英]Read Socket stream data and read first 2 bytes, find rest of message length

如何從輸入流中讀取前2個字節並將2個字節的數據轉換為實際的int長度值,然后讀取其余消息並將其復制到字節數組中。 數據數組的其余部分應在從流中讀取前2個字節后定義,有人知道高效的邏輯嗎?

使用DataInputStream. 使用readUnsignedShort()方法返回長度字,然后使用readFully()方法讀取以下數據。

這將從字節數組創建一個字符串。 根據需要進行調整。

InputStream in;
try {
    in = socket.getInputStream();
    DataInputStream dis = new DataInputStream(in);

    int len = dis.readInt();
    byte[] data = new byte[len];
    if (len > 0) {
       dis.readFully(data);
    }           
    String sReturn = new String(data); 
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM