I am trying to implement a server-client connection with spp.
After initializing the server, I start the thread, which first listens for clients, and then receives data from them. It looks like this:
public final void run() {
while (alive) {
try {
System.out.println("Awaiting client connection...");
client = server.acceptAndOpen();
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 works great because I can receive messages. What bothers me is how the thread will eventually die when the device goes out of range?
First, the call is receive.read(buffer)blocked, so the thread waits until it receives any data. If the device is out of range, it will never continue to check if the time has been interrupted.
Secondly, it will never close the connection, i.e. the server will not accept the device after it returns to range.