LastExceed
07/29/2020, 10:34 AMByteReadChannel
? 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 ?edenman
07/29/2020, 11:56 AMprivate suspend fun ByteReadChannel.readEntireUTF8(): String {
val sb = StringBuilder()
while (!isClosedForRead) {
sb.append(readUTF8Line() ?: "")
}
return sb.toString()
}
LastExceed
07/29/2020, 12:00 PMwriteChannel.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 opsuspend 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