Bluetooth in Java Mobile: Handling connections that go out of range

Posted by Albus Dumbledore on Stack Overflow See other posts from Stack Overflow or by Albus Dumbledore
Published on 2010-12-27T09:08:10Z Indexed on 2011/01/02 8:53 UTC
Read the original article Hit count: 273

Filed under:
|
|
|
|

I am trying to implement a server-client connection over the spp.

After initializing the server, I start a thread that first listens for clients and then receives data from them. It looks like that:

public final void run() {
    while (alive) {
        try {
            /*
             * Await client connection
             */
            System.out.println("Awaiting client connection...");
            client = server.acceptAndOpen();

            /*
             * Start receiving data
             */
            int read;
            byte[] buffer = new byte[128];
            DataInputStream receive = client.openDataInputStream();
            try {
                while ((read = receive.read(buffer)) > 0) {
                    System.out.println("[Recieved]: "
                            + new String(buffer, 0, read));

                    if (!alive) {
                        return;
                    }
                }
            } finally {
                System.out.println("Closing connection...");
                receive.close();
            }
        } catch (IOException e){
            e.printStackTrace();
        }
    }
}

It's working fine for I am able to receive messages. What's troubling me is how would the thread eventually die when a device goes out of range?

Firstly, the call to receive.read(buffer) blocks so that the thread waits until it receives any data. If the device goes out of range, it would never proceed onward to check if meanwhile it has been interrupted.

Secondly, it would never close the connection, i.e. the server would not accept the device once it goes back in range.

Thanks! Any ideas would be highly appreciated!

Merry Christmas!

© Stack Overflow or respective owner

Related posts about java

Related posts about multithreading