how do i read a string from a `ByteReadChannel` ? ...
# ktor
l
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
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
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
543 Views