gpt4 book ai didi

android - 通过BluetoothSocket接收的数据已损坏

转载 作者:行者123 更新时间:2023-12-03 12:08:48 25 4
gpt4 key购买 nike

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

因此,为了找到一种解决方法,我开始加载并发送文件块。直到我继续打开接收到的文件之前,它似乎也按照我想要的方式工作。最早收到的照片之一是这个corrupted image。但是,大多数其他照片或APK文件(无论杂项“大”文件)根本无法打开。我相信问题出在发送数据块的循环逻辑中。可能我错过了一些简单的东西,只是重复发送了相同的数据块?

请在下面查看我的代码,让我知道您是否能发现我所犯的错误。这是开始发送的线程:

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())
}

在文件的大块中,读取int内存,给定标题,并使用 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。

最佳答案

我应该像这样循环

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
}

如果返回 bool 值,则更像是
if (!BluetoothService.send(b, 0, numRead) )
{
// handle error

break;
}

关于android - 通过BluetoothSocket接收的数据已损坏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48361058/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com