简体   繁体   中英

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

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, ie the server would not accept the device once it goes back in range.

When the remote device goes out of range, after the link supervision timeout expires, the local stack should close the connection. Depending on the JSR-82 implementation, receive.read(buffer) will return -1 or will throw an IOException . You can simulate this by turning off the remote device or moving it out of range.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM