Using `TcpSocketBuilder` and then the created `Byt...
# ktor
e
Using
TcpSocketBuilder
and then the created
ByteReadChannel
, how do I read a
UInt
?
a
so ByteReadChannel has a
readInt()
member function https://api.ktor.io/ktor-io/io.ktor.utils.io/-byte-read-channel/index.html#598794336%2FFunctions%2F599479352, but no
readUInt()
member or extension function And so, at a guess, you could try reading the number of bytes required UInt.SIZE_BYTES and then convert them into a UInt
a
Copy code
channel.readInt().toUInt()
👍 1
e
Thanks! I guess the second solution would be simpler, I just don't want to mess with the binary representation
I need those unsigned ints to extract flags, bit by bit
a
Copy code
channel.readInt().toUInt()
ahh yeah, if that works 👍. I assumed it wouldn’t because
UInt.MAX_VALUE
is of course larger than
Int.MAX_VALUE
- but I guess the byte representation is the same
✔️ 1
e
Follow up question: there doesn't seem to be an easy to use method to read an arbitrary amount of bytes into a byte array or buffer. Or maybe I can't find it
a
another option for UInt, you could do
readPacket(UInt.SIZE_BYTES)
https://api.ktor.io/ktor-io/io.ktor.utils.io/-byte-read-channel/read-packet.html which returns a ByteReadPacket, which has a readUInt() extension
e
Is readPacket the most generic function to read n bytes?
There is also
readFully
which accepts a buffer/byte array. Not sure what's the difference
I made it work correctly with
readPacket
. Thanks both! Now I'd like to perform a write. Is there a way to concatenate two
ByteReadPacket
into a single
ByteReadPacket
? I need to perform an "atomic" write
Solved with the following code, which uses another builder
Copy code
sendChannel.writePacket {
  if (serializable.autosize()) {
    writeUInt(outputStream.getWrittenBytes().toUInt())
  }

  writePacket(payloadBuilder.build())
}