سؤال

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.

هل كانت مفيدة؟

المحلول

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.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top