0

我正在使用下面的代码从连接的套接字读取数据,并且在执行 System.arraycopy(tempBuffer, 0, buffer, 0, byteRead) 代码后我在缓冲区变量中接收的数据长度为 41 个字节。发送系统正在发送 43 个字节。任何人都知道为什么 arraycopy 会切断其他字节?

public class BluetoothClientSocket{
     private class ConnectedThread extends Thread {

          private final BluetoothSocket mmSocket;
          private final InputStream mmInStream;
          private final OutputStream mmOutStream;

         public ConnectedThread(BluetoothSocket socket) {
               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) {
            //handle exception logic
            }

            mmInStream = tmpIn;
            mmOutStream = tmpOut;
          }

         public void run(){
             byte[] tempBuffer = new byte[1024];
             byte[] buffer = null;
             int byteRead;

             while (true) {
                try {
                        InputStream itStrm = mmInStream;
                        byteRead = mmInStream.read(tempBuffer);
                        if(byteRead > 0){
                             buffer = new byte[byteRead];
                             System.arraycopy(tempBuffer, 0, buffer, 0, byteRead);
                        }
                   }
                   catch(Exception ex){
                       //handle exception logic
                   }
              }
          }
     }
}
4

1 回答 1

6

发送系统正在发送 43 个字节。

这并不意味着您在一次调用read.

任何人都知道为什么 arraycopy 会切断其他字节?

它不是。我怀疑你会发现它byteRead是 41,这意味着“问题”发生在arraycopy参与之前。

我希望您在下一次调用read.

或者你的代码在另一端是错误的,你只发送 41 个字节开始。

于 2012-07-24T19:11:27.697 回答