Archived
1
0
Fork 0
This repository has been archived on 2025-03-02. You can view files and clone it, but you cannot make any changes to it's state, such as pushing and creating new issues, pull requests or comments.
uranos/blokk-server/src/main/kotlin/space/blokk/net/FramingCodec.kt

34 lines
1 KiB
Kotlin

package space.blokk.net
import io.netty.buffer.ByteBuf
import io.netty.channel.ChannelHandlerContext
import io.netty.handler.codec.ByteToMessageCodec
import space.blokk.net.MinecraftDataTypes.readVarInt
import space.blokk.net.MinecraftDataTypes.varIntReadable
import space.blokk.net.MinecraftDataTypes.writeVarInt
class FramingCodec : ByteToMessageCodec<ByteBuf>() {
private var currentLength: Int? = null
override fun encode(ctx: ChannelHandlerContext, msg: ByteBuf, out: ByteBuf) {
out.writeVarInt(msg.readableBytes())
msg.readerIndex(0)
out.writeBytes(msg)
}
override fun decode(ctx: ChannelHandlerContext, msg: ByteBuf, out: MutableList<Any>) {
var length = currentLength
if (length == null) {
if (msg.varIntReadable()) {
length = msg.readVarInt()
currentLength = length
} else return
}
if (msg.readableBytes() >= length) {
out.add(msg.readBytes(length))
currentLength = null
}
}
}