Search code examples
socketskotlintcp

Trimming empty elements off end of byte array - Kotlin


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
}

Solution

  • If writeData reads from the buffer, it doesn't have to read everything. You can just pass count to it and change the implementation to only write up to count 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 I guess.

    Also, I guess you aren't showing all the code but you should read from mInStream in a loop (instead of just once) to be sure to read everything.