我正在尝试通过 spp 实现服务器-客户端连接。
初始化服务器后,我启动了一个线程,该线程首先侦听客户端,然后从它们接收数据。它看起来像这样:
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();
}
}
}
它工作正常,因为我能够接收消息。令我困扰的是,当设备超出范围时,线程最终会如何死掉?
首先,调用receive.read(buffer)
阻塞,以便线程等待,直到它收到任何数据。如果设备超出范围,它将永远不会继续检查是否同时被中断。
其次,它永远不会关闭连接,即一旦设备回到范围内,服务器就不会接受设备。