编程语言
首页 > 编程语言> > Java Mobile中的蓝牙:处理超出范围的连接

Java Mobile中的蓝牙:处理超出范围的连接

作者:互联网

我正在尝试通过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)的调用将阻塞,以便线程等待直到接收到任何数据为止.如果设备超出范围,它将永远不会继续检查它是否已被中断.

其次,它将永远不会关闭连接,即一旦服务器返回范围,服务器将不会接受该设备.

解决方法:

当远程设备超出范围时,链路监视超时到期后,本地堆栈应关闭连接.根据JSR-82的实现,receive.read(buffer)将返回-1或将引发IOException.您可以通过关闭远程设备或将其移出范围来模拟此情况.

标签:multithreading,bluetooth,java-me,java,jsr82
来源: https://codeday.me/bug/20191208/2094704.html