[英]How to read data coming from TCP Socket separated by a specific delimeter
我需要使用TCP上的套接字連接從服務器讀取字節數據。 數據采用字節流的形式,該字節流由一個或多個值為255(0xFF)的八位字節定界
我正在使用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條件,以便知道已經收到一個數據包並開始處理該數據包。 我不知道我將要收到的消息的長度,我也不知道傳入消息中的長度。
請幫助我讀取這種類型的字節數據。 任何幫助,我們都感激不盡。
如果您的定界符為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 = "";
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.