I am using Sockets for transferring data over Wifi in my android app, I have set the Buffer size to around 10MB and here is my code for sending data.
// Sending data from a file in chunks, PREFERRED_CHUNK_SIZE is [1024 * 1024 * 10]
var fileSize = fileList[index].totalSize
val buffer = ByteArray(SocketConstants.PREFERRED_CHUNK_SIZE)
var length: Int
do {
length = stream.read(buffer, 0, min(buffer.size, fileSize))
bos.write(buffer, 0, length)
fileSize -= length
} while (fileSize != 0)
stream.close()
I am reusing the same code for multiple file transfer, the condition filesize,= 0 makes sure I read only that much bytes for a single file and thus I have used that min function lets say I want to send 36 MB it is sent as 10(10485760 bytes), 10(10485760 bytes), 10(10,485,760 bytes). 6.
Below is my code for receiver:
var fileSize = file.totalSize
var current: Int
var offset = 0
val byteArray = ByteArray(SocketConstants.PREFERRED_CHUNK_SIZE)
val bufferedInputStream = BufferedInputStream(inputStream)
do {
current = bufferedInputStream.read(byteArray, 0, min(byteArray.size, fileSize))
// outputStream.write(byteArray, 0, current) To ignore file write for now
fileSize -= current
offset += current
println("Length: $current")
file.bytesDownloaded = offset
updateList(offset)
} while (fileSize != 0)
outputStream.flush()
outputStream.close()
When reading I am getting really small chunks of bytes, 1358, 1358, 1358, 1358, 1358.
This is really slow, I don't understand what is causing inputStream.read() such small reads.
I have already set the sender and receiver buffer size for SocketServer and Socket instance. But there was no difference in the results
After looking for a solution for few days and trying multiple ways to increase the speed when read is called on inputstream I finally discovered the solution.
Thanks Gerd in comments who kind of helped me start thinking about the strength of a Wifi connection.
What I found was, if you connect to wifi using Android Wifi Manager, the connection established is a slow connection and you wouldn't even see in the task bar if you are connected to an actual wifi.
To overcome it, I manually connected to hotspot using Wifi settings in the mobile and that has better speed.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.