I have the following Bluetooth Server class that extends a Thread to listen for incoming stream:
class SeverThread extends Thread{
bytes[] inBuffer = new bytes[1024];
int bytes;
while(true){
try{
bytes = inputStream.read(inBuffer);
}catch(IOException e){
// handle exception
}
System.out.println(new String(inBuffer));
}
}
The problem with this implementation:
When client first sends "Sanjeev" , output is "Sanjeev". Cool. After that, the client sends smk, the output now is smkjeev. Note that first 3 letters – san – have become smk. Now when the client sends hell, the output is helleev. If the client again sends "Sanjeev" then output is "Sanjeev" , because length of received string is same as the used space inside the buffer.
This is the expected behavior based on above code. But it’s an unintended bug. I want the outputs to be Sanjeev , smk and hello respectively. The problem is apparent. The same buffer in memory is being used to take all the incoming words.
Any suggestions on how to fix this? Possible approaches:
- Clear or refresh the buffer for every loop inside
while(true). I don’t know how to do this. - Move the declaration of
inBufferinside thewhileloop. But this will continuously allocate memory, a big wastage.
Thanks.
How about this ?