2013-12-09 100 views
1

有沒有一種方法可以發送多個消息OutputStream.write(bytes[]),例如當我調用兩次我的函數來編寫func.write("hi"); func.write(" how are you");,我收到消息「concateneted」像這樣:"hi how are you",但我想兩個不同的消息,是有辦法做到這一點,而不在我的消息中的分離,我的意思是,當其它設備接收的消息知道,這裏是我的代碼(其Android的藍牙樣品):Android outputStream.write發送多條消息

private class ConnectedThread extends Thread { 
    private final BluetoothSocket mmSocket; 
    private final InputStream mmInStream; 
    private final OutputStream mmOutStream; 

    public ConnectedThread(BluetoothSocket socket, String socketType) { 
     Log.d(TAG, "create ConnectedThread: " + socketType); 
     mmSocket = socket; 
     InputStream tmpIn = null; 
     OutputStream tmpOut = null; 

     // Get the BluetoothSocket input and output streams 
     try { 
      tmpIn = socket.getInputStream(); 
      tmpOut = socket.getOutputStream(); 
     } catch (IOException e) { 
      Log.e(TAG, "temp sockets not created", e); 
     } 

     mmInStream = tmpIn; 
     mmOutStream = tmpOut; 
    } 

    public void run() { 
     Log.i(TAG, "BEGIN mConnectedThread"); 
     byte[] buffer = new byte[1024]; 
     int bytes; 

     // Keep listening to the InputStream while connected 
     while (true) { 
      try { 
       // Read from the InputStream 
       bytes = mmInStream.read(buffer); 

       // Send the obtained bytes to the UI Activity 
       mHandler.obtainMessage(BluetoothChat.MESSAGE_READ, bytes, -1, buffer) 
         .sendToTarget(); 
      } catch (IOException e) { 
       Log.e(TAG, "disconnected", e); 
       connectionLost(); 
       // Start the service over to restart listening mode 
       BluetoothChatService.this.start(); 
       break; 
      } 
     } 
    } 

    /** 
    * Write to the connected OutStream. 
    * @param buffer The bytes to write 
    */ 
    public void write(byte[] buffer) { 
     try { 
      mmOutStream.write(buffer); 

      // Share the sent message back to the UI Activity 
      mHandler.obtainMessage(BluetoothChat.MESSAGE_WRITE, -1, -1, buffer) 
        .sendToTarget(); 
     } catch (IOException e) { 
      Log.e(TAG, "Exception during write", e); 
     } 
    } 

    public void cancel() { 
     try { 
      mmSocket.close(); 
     } catch (IOException e) { 
      Log.e(TAG, "close() of connect socket failed", e); 
     } 
    } 
} 

回答

0

電話:

mmOutStream.flush() 

每個消息部分之後。

public void write(byte[] buffer) { 
    try { 
     mmOutStream.write(buffer); 

     //send what is already in buffer 
     mmOutStream.flush(); 

     // Share the sent message back to the UI Activity 
     mHandler.obtainMessage(BluetoothChat.MESSAGE_WRITE, -1, -1, buffer) 
       .sendToTarget(); 
    } catch (IOException e) { 
     Log.e(TAG, "Exception during write", e); 
    } 
} 

docs

  • 平齊()

    (刷新此輸出流並強制地寫出來的任何緩衝的輸出字節沖洗的常規協定是。調用它表明,如果先前寫入的任何字節已通過輸出流的實現進行緩衝,則應立即將這些字節寫入其預期的目標位置。

+0

Flush沒有解決我的連接問題。有沒有其他解決方案。 – Crawler

+0

如果您正在爲接收端編寫代碼,可能會像回車一樣添加消息終止符字節。在代碼的接收端查找該字節,您將知道這些消息之間存在分隔。 – Joules