通过BluetoothSocket接收的数据已损坏

时间:2018-01-20 21:00:55

标签: android sockets kotlin

我一直在编写一个应用程序,它应该通过蓝牙将文件发送到运行相同应用程序的另一台设备。我有成功发送文件但有一个大问题...当我发送一个太大的文件时,我得到了一个内存不足的例外。

因此,为了找到解决方法,我开始加载并发送文件块。它似乎按照我想要的方式运行,直到我继续打开收到的文件。首批收到的照片之一看起来像corrupted image。但大多数其他照片,或APK文件(无论misc。"大"文件)根本不打开。我相信问题出现在我的循环逻辑中,即发送数据块。可能我错过了一些简单的东西,只是反复发送相同的数据块?

请查看下面的代码,如果您能发现我正在制作的错误,请告诉我。这是开始发送的线程:

thread {
    val file = fileManager.select(fileName)
    val inStream = file.inputStream(
    val length = file.length()

    val b = ByteArray(1000000)

    var count = 0 //used to keep track of progress through file
    var off = 0
    var numRead = 0

    val notificationManager = activity.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
    val notificationBuilder = NotificationCompat.Builder(activity)
    notificationBuilder.setContentTitle("File Transfer")
            .setSmallIcon(R.drawable.abc_btn_radio_material)
            .setContentText("Sending $fileName...")
            .setOngoing(true)
            .setProgress(length.toInt(), 0, false)
    notificationManager.notify(BTS_Constants.NOTIFICATION_ID, notificationBuilder.build())

    val header = "${BTS_Constants.START_MARKER}$fileName:$length:".toByteArray()
    BluetoothService.send(header, header.size.toLong(), header.size)

    while (count < length){
            try {
                numRead = inStream.read(b, off, 1000000)
                off+=numRead // is problem here?
                count+=numRead
                if (!(numRead>=0))break
                off = 0
            }catch (ae:ArrayIndexOutOfBoundsException) {
                BluetoothService.log("end of file reached", ae)
            }
        if (BluetoothService.send(b, length, count)){
            Log.d(TAG, "count: $count\nlength: ${length.toInt()}")
            notificationBuilder.setProgress(length.toInt(), count, false)
            notificationManager.notify(BTS_Constants.NOTIFICATION_ID, notificationBuilder.build())
        }
    }
    notificationBuilder.setProgress(0, 0, false)
            .setOngoing(false)
            .setContentText("Finished sending")
    notificationManager.notify(BTS_Constants.NOTIFICATION_ID, notificationBuilder.build())
}

在文件的一个块中读取内存,给定一个头并使用BluetoothService.send()函数发送。如果send()返回true,则更新进度。这是BluetoothService.send()

@Synchronized fun send(bytes:ByteArray, fileLength:Long, progress:Int):Boolean{
    var synThread:ConnectedThread? = null
    synchronized(this@BluetoothService){
        synThread = mConnectedThread
    }

    var success:Boolean

    try {
        synThread?.write(bytes, progress, fileLength.toInt())
        success = true
    }catch (e:Exception){
        success = false
    }

    return success
}

send函数调用synThread的write()函数。 synThreadConnectedThread?宾语。以下是包含写函数定义的ConnectedThread的定义:

class ConnectedThread(val socket: BluetoothSocket) : Thread(){
    var fileName:String = ""
    var fileLength:Int = 0

    val inStream:InputStream
    val outStream:OutputStream
    val outBuffer:ByteArray
    var inBuffer:ByteArray
    var fOut:FileOutputStream? = null
    var bytes:Int = 0
    var active = true
    val notifyManager = BluetoothService.context?.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
    var notifyBuilder:NotificationCompat.Builder? = null

    init {
        inStream = socket.inputStream
        outStream = socket.outputStream
        outBuffer = ByteArray(1000000)
        inBuffer = ByteArray(1024)
        notifyBuilder = NotificationCompat.Builder(BluetoothService.context)
        notifyBuilder?.setSmallIcon(R.drawable.abc_btn_radio_material)
                ?.setContentTitle("Downloading")
    }

    override fun run() {
        BluetoothService.log("$this waiting to read . . .")
        while (active){
            try {
                bytes += inStream.read(inBuffer)
                var header = String(inBuffer)
                if (header.startsWith(BTS_Constants.START_MARKER)){
                    this.fileName = header.substringAfter(BTS_Constants.START_MARKER).substringBefore(":")
                    this.fileLength = (header.substringAfter(":").substringBeforeLast(":")).toInt()
                    val path = "${Environment.DIRECTORY_DOWNLOADS}/$fileName"
                    val outFile = File(Environment.getExternalStoragePublicDirectory(path).toURI())
                    if (outFile.exists()){
                        BluetoothService.log("file already exists")
                    }else{
                        outFile.createNewFile()
                    }
                    fOut = outFile.outputStream()
                    inBuffer = ByteArray(1000000)
                    bytes = 0
                    notifyBuilder!!.setContentText("file: $fileName")
                            .setProgress(0, 0, true)
                            .setOngoing(true)
                            .setVibrate(LongArray(1){
                                10000L
                            })
                    notifyManager.notify(BTS_Constants.NOTIFICATION_ID, notifyBuilder!!.build())
                    BluetoothService.log("name = $fileName, length = $fileLength")
                }else if(bytes>=fileLength){
                    notifyBuilder!!.setProgress(0, 0, false)
                            .setContentText("Download complete")
                            .setOngoing(false)
                    notifyManager.notify(BTS_Constants.NOTIFICATION_ID, notifyBuilder!!.build())
                    //possibly save last bytes of file here
                }else{
                    BluetoothService.log("bytes: $bytes read: $inBuffer")
                    fOut?.write(inBuffer)
                }
                BluetoothService.log("read $bytes bytes: $inBuffer")
            }catch (ioe:IOException){
                BluetoothService.log("failed to read from $socket", ioe)
                cancel()
            }
        }
    }

    //WRITE FUNCTION
    fun write(bytes:ByteArray, progress: Int, length:Int){
        BluetoothService.log("writing bytes from $this")
        outStream.write(bytes)
        outStream.flush()
        BluetoothService.log("bytes written")
    }

    fun cancel(){
        BluetoothService.log("closing socket, read may fail - this is expected")
        active = false
        socket.close()
    }
}

所以我再次相信这是在我的循环逻辑中的某个地方犯了一个错误,但我看不到它。请帮我找到这个问题和解决方案。谢谢。

更新循环:

while (totalRead < length){
    try {
    numRead = inStream.read(b, 0, b.size)
    if (numRead<=0)break
    totalRead+=numRead
         }catch (ae:ArrayIndexOutOfBoundsException) {
    BluetoothService.log("end of file reached", ae)
             }
    if (BluetoothService.send(b, 0, numRead)){
    Log.d(TAG, "totalRead: $totalRead\nlength: ${length.toInt()}")
    notificationBuilder.setProgress(length.toInt(), totalRead, false)
    notificationManager.notify(BTS_Constants.NOTIFICATION_ID, notificationBuilder.build())
       }else{
    BluetoothService.log("Error sending data", BluetoothServiceException())
                 }
                }

并更新了发送功能:

@Synchronized fun send(bytes: ByteArray, offset: Int, length: Int):Boolean{
    var synThread:ConnectedThread? = null
    synchronized(this@BluetoothService){
        synThread = mConnectedThread
    }

    var success:Boolean

    try {
        synThread?.write(bytes, 0, length)
        success = true
    }catch (e:Exception){
        success = false
    }

    return success
}

更新写功能:

fun write(bytes: ByteArray, offset: Int, length: Int){
    BluetoothService.log("writing bytes from $this")
    outStream.write(bytes, offset, length)
    outStream.flush()
    BluetoothService.log("bytes written")
}

我注意到收到的照片属性中有一些有趣的东西。发送前文件的大小,以及收到文件的大小。发送的照片大小为5.05MB,收到后显示为526 MB。

1 个答案:

答案 0 :(得分:0)

这应该是一个像

这样的循环
while ( totalRead < length ) 
   {
   int numRead = inStream.read(b, 0, 1000000)

   if ( numread <= 0 )
       break;

   totalRead += numRead;

   int nsend = BluetoothService.send(b, 0, numRead);

   if ( nsend != numRead ) 
       well then you should make another loop here to send all
   }

如果返回布尔值,则更像是

if (!BluetoothService.send(b, 0, numRead) )
{
 // handle error

 break;
}