我正在尝试通过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)
的调用会阻塞,以便线程等到收到任何数据。如果设备超出范围,它将永远不会继续检查它是否同时被中断。
其次,它永远不会关闭连接,即服务器一旦返回范围就不会接受该设备。
答案 0 :(得分:3)
当远程设备超出范围时,在链路监督超时到期后,本地堆栈应关闭连接。根据JSR-82的实现,receive.read(buffer)
将返回-1或将抛出IOException
。您可以通过关闭远程设备或将其移出范围来模拟此情况。