sanjeev mk
sanjeev mk

Reputation: 4336

Bluetooth server incoming buffer handling

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:

  1. Clear or refresh the buffer for every loop inside while(true). I don't know how to do this.
  2. Move the declaration of inBuffer inside the while loop. But this will continuously allocate memory, a big wastage.

Thanks.

Upvotes: 0

Views: 750

Answers (1)

Dennis Mathews
Dennis Mathews

Reputation: 6975

How about this ?

bytes = inputStream.read(inBuffer);
inBuffer[bytes] = '\0';

Upvotes: 1

Related Questions