In Kotlin, When writing TCP server program, server is not aware of the data length is going to receive. I intialized byte array with size of 1024. But i may receive, 5 bytes also. When I read in some other links, says that we need to maintain the separate buffer and perform copy to the new buffer and write the data from the new buffer.
Is this the only way to do in Kotlin as well or we have other better options?
val buffer = ByteArray(1024)
val count = mInStream?.read(buffer)
if (count > 0) {
writeData(buffer)
}
fun writeData(buff:Bytearray){
//the data in buff will be written to the bluetooth socket
}
countalready tells you how many bytes were written to the buffer, so you know which ones you want to read. How to do it kinda depends on what you want to do with these bytes. What iswriteDatahere? - JoffreywriteData, I think I had figured out the signature :D In any case, why don't you simply passcounttowriteDataso it only writes the correct bytes to the socket? You could also pass an offset if you want to start from anywhere in the buffer, but in this case you only need to start from the beginning. - Joffrey