I have a TCP Socket implementation in Kotlin and use the code below to read a String (using a BufferedReader):
val readBuffer = BufferedReader(InputStreamReader(socket.inputStream))
private fun readLine(reader: BufferedReader): String? {
val data = CharArray(4096)
val count = reader.read(data)
if(count < 0) {
return null
}
return String(data, 0, count)
}
readLine(readBuffer)
My assumption here is that the message I'm going to receive never exceeds 4096 bytes (which is the case), but I was wondering whether this is the correct approach? What happens when the message would exceed 4096 bytes? Is there any other value I could use to initialise the CharArray? I know InputStream has an available() method which returns an estimate of the number of bytes that can be read (or skipped over) from this input stream without blocking by the next invocation of a method for this input stream [1]. But as it's an estimation, I am not confident is safe to use in this case.
Any insights appreciated!
[1] https://docs.oracle.com/javase%2F7%2Fdocs%2Fapi%2F/java/io/InputStream.html#available()
StringBuilder,ByteArrayOutputStream, etc.read()aCharArraywith a size of4096, and more data is available (e.g. 6144 bytes), what will be the expected behaviour? Will the read fill myCharArraywith 4096 bytes, return 4096 and give the next 4096 bytes on a secondread()(which will return 2048)? Or will there be an Overflow exception on the firstread()(because more bytes are available and my CharArray can't store them)?reader.read(data)will place intodatano more characters than the length ofdata, and it will return how many characters it put indata. If more data is available, you will have to callreadagain. This is usually done in a loop. When EOF or end of stream is reached, nothing will be written intodataand -1 is returned. No exception is thrown.readcan return 0 is if you give it a zero-length array as an argument. Otherwise, it will block until some data is available.