1
votes

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
}
1
I'm not entirely sure I understand your requirements here. count already 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 is writeData here? - Joffrey
Hi Joffrey, Thanks for the response, Now added writeData(). The received data from TCP socket will be written into the Bluetooth socket. For example, If I receive 5 bytes from read, I cannot write entire buffer to Bluetooth socket. I should resize the buffer to the received data or I should copy to the another buffer and write. So the question is copying the only way or some easiest way available in Kotlin. In Java, there is no other way. - RKVM
I was interested in the implementation of writeData, I think I had figured out the signature :D In any case, why don't you simply pass count to writeData so 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

1 Answers

-1
votes

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.