繁体   English   中英

阅读蓝牙套接字android后写一个输出流

[英]Write an outputstream after reading bluetooth socket android

我想从设备读取后(通过Bluetooth套接字)进行写入问题是,当套接字关闭时,while(true)完成,因此我无法再次写入。

这是代码:

        try {
            // This will block until it succeeds in connecting to the device
            // through the bluetoothSocket or throws an exception
            bluetoothSocket.connect();
            try {
                connectingThread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            outstream = bluetoothSocket.getOutputStream();
            outstream.write("P".getBytes());
            instream = bluetoothSocket.getInputStream();
            byte[] buffer = new byte[128];  // buffer store for the stream
            int bytes; // bytes returned from read()
            String readMessage = "";

             // Keep listening to the InputStream until an exception occurs
            while (true) {
                try {
                    // Read from the InputStream
                    bytes = instream.read(buffer);
                    if(bytes!= -1){
                    // Send the obtained bytes to the UI activity
                    readMessage = new String(buffer, 0, bytes);

                    arrayList.add(readMessage);
                    biodyMsg = TextUtils.join("", arrayList);
                    }

                } catch (Exception e) {

                    Log.d("Read Error", e.toString());

                }finally {
                    outstream = bluetoothSocket.getOutputStream();
                    outstream.write("F".getBytes());
                }
                break;
            }

        } catch (IOException connectException) {
            connectException.printStackTrace();
            try {    
                bluetoothSocket.close();
            } catch (IOException closeException) {
                closeException.printStackTrace();
            }
        }

Logcat

你能帮助我吗

while (true)循环终止的唯一方法是通过break语句或获取未捕获的异常,并且您没有提到获取一个。 此代码中有两个可能的例外:

  • IOException :但是,使用此代码获取IOException的唯一方法是对等方重置连接。
  • 构造String ,如果bytes为负,则为ArrayIndexOutOfBoundsException ,可以为: 但是您也没有提到这一点。

您的实际问题是您没有检查-1的bytes ,这表示流结束,而这又表明对等体已关闭连接,这反过来又表明您应关闭套接字并断开连接。读取循环。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM