https://kotlinlang.org logo
#ktor
Title
# ktor
l

LastExceed

07/29/2020, 10:34 AM
how do i read a string from a
ByteReadChannel
? i know there is
.readUTF8Line()
but what if my string contains newlines ? do i have to convert the string to a bytearray and send that (preceded with its size) or is there a better way ?
e

edenman

07/29/2020, 11:56 AM
this is what i do:
Copy code
private suspend fun ByteReadChannel.readEntireUTF8(): String {
    val sb = StringBuilder()
    while (!isClosedForRead) {
      sb.append(readUTF8Line() ?: "")
    }
    return sb.toString()
  }
been working well in production for the last couple months but my N is still very small so ymmv
oh also i just re-read your message and i imagine you could just add a sb.append(“\n”) in that loop if you care about the newlines?
l

LastExceed

07/29/2020, 12:00 PM
what i want is something like
writeChannel.writeString(myString)
on the sender side and val
val myString = readChannel.readString()
on the receiver side without having to worry about the content of the string. i achieved this by creating such extension function that do what i explained in op
Copy code
suspend fun ByteReadChannel.readString(): String {
	ByteArray(readInt()).let {
		readFully(it)
		return it.toString(Charset.forName("UTF-8"))
	}
}

suspend fun ByteWriteChannel.writeString(string: String) {
	string.toByteArray().let {
		writeInt(it.size)
		writeFully(it)
	}
}
but it feels messy, and i honestly cant imagine that ktor doesnt already have some way to do this properly
452 Views