2016-05-06 120 views
0

我想在从设备读取数据后(通过蓝牙插座) 问题是,当(套接字关闭时,while(true)完成,所以我不能再次写入。在阅读蓝牙插座后写一个输出流android

这是代码:

 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

你能帮我

回答

0

一个while (true)环可以终止是通过break声明,或通过获取未捕获的异常的唯一途径,你还没有提到过。有代码中有两处可能的例外:

  • IOException:但你可以使用此代码IOException的唯一途径是,如果对重置的连接。
  • ArrayIndexOutOfBoundsException当构建String时,如果bytes是负数,它可以是:见下文;但你还没有提到这一点。

您的实际问题是,你是不是为-1检查bytes,这表明流的结束,这反过来将表明对已经关闭了连接,这又表明你应该关闭套接字并跳出读取循环。

+0

对不起,没有把异常:java.io.IOException:损坏的管道 –

+0

因此,对端已重置连接。你有什么问题? – EJP

+0

在完成阅读后我可以在连接重置之前写入我想发送“F”的信息 –