2017-07-17 59 views
0

我需要使用基於TCP的套接字連接讀取來自服務器的數據的字節數。數據是以字節流的形式由一個或多個八位字節分隔的,值爲255(0xFF)如何讀取來自TCP套接字的數據,並由特定的分隔符分隔

我正在使用BufferedInputSream讀取數據。我的代碼的一部分低於:

String messageString = ""; 
DataInputStream in = new DataInputStream(new BufferedInputStream(socket.getInputStream())); 
byte[] bytes = new byte[16 * 1024]; 
System.out.println("Receiving Bytes"); 
    while(true) 
    { 
    bytesRead = in.read(bytes); 
    messageString += new String(bytes,0,bytesRead); 
    if (<SOME CONDITION TO KNOW THAT DELIMITER IS RECEIVED>) 
     { 
     System.out.println("Message Received: " + messageString); 
     //Proceed to work with the message 
     messageString = ""; 
     } 
    } 

我需要的IF條件讓我知道,我收到一個數據包,並開始處理相同。 我不知道我將收到的消息的長度,我也沒有收到消息中的信息長度。

請幫我讀這種類型的字節數據。 任何幫助是真正的讚賞。

回答

0

如果你的分隔符是255你可以檢查你剛纔讀該值的數據:

bytesRead = in.read(bytes); 
int index= bytes.indexOf(255); 
if (index<0) 
{ 
    messageString += new String(bytes,0,bytesRead); 
} 
else //<SOME CONDITION TO KNOW THAT DELIMITER IS RECEIVED>) 
{ 
    messageString += new String(bytes,0,index); 
    System.out.println("Message Received: " + messageString); 
    //Proceed to work with the message 
    messageString = ""; 
} 
相關問題