I need to read Bytes of data from a Server using Socket connection over TCP. The data is in the form of a Byte Stream delimited by delimited by one or more octets with a value of 255 (0xFF)
I am using BufferedInputSream to read the data. A part of my code is below:
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 = "";
}
}
I need the IF condition so that I know that I have received one data packet and start processing the same. I don't know the length of the message that I am going to receive neither I have the information to the length in the incoming message.
Please help me read this type of byte data. Any help is truly appreciated.
If your delimiter is 255 you can just check the data you just read for that value:
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 = "";
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.