Skip to content

Instantly share code, notes, and snippets.

@ThatsNoMoon
Created March 2, 2019 03:46
Show Gist options
  • Save ThatsNoMoon/2aa1c34cde33838d5ca872d3c9a2479a to your computer and use it in GitHub Desktop.
Save ThatsNoMoon/2aa1c34cde33838d5ca872d3c9a2479a to your computer and use it in GitHub Desktop.
class IncomingPacket(opcode: Int, type: PacketType, buffer: ByteBuf) : Packet(opcode, type, buffer) {
/**
* Reads a byte from the buffer and returns it
*/
fun readByte(): Byte = buffer.readByte()
/**
* Reads an integer from the buffer and returns it
*/
fun readInt(): Int = buffer.readInt()
}
class OutgoingPacket(opcode: Int, type: PacketType, buffer: ByteBuf) : Packet(opcode, type, buffer) {
/**
* Constructs a [PacketType.STANDARD] packet a specified id
*/
constructor(opcode: Int) :
this(opcode, PacketType.STANDARD, Unpooled.buffer())
/**
* Constructs a packet with a specified id and type
*/
constructor(opcode: Int, type: PacketType) :
this(opcode, type, Unpooled.buffer())
/**
* Writes another buffer to the buffer
*/
fun writeBytes(data: ByteBuf) = buffer.writeBytes(data)
/**
* Writes a byte to the buffer
*/
fun writeByte(data: Int): ByteBuf = buffer.writeByte(data)
/**
* Writes an integer to the buffer
*/
fun writeInt(data: Int): ByteBuf = buffer.writeInt(data)
/**
* Writes a string to the buffer
*/
fun writeString(data: String) {
buffer.writeBytes(data.toByteArray())
buffer.writeByte(0)
}
}
open class Packet(val opcode: Int, val type: PacketType, val buffer: ByteBuf, val length: Int) {
/**
* Constructs a packet
* @param opcode the numerical identifier of the packet
* @param type the type of packet this is
* @param buffer the buffer of bytes
* @constructor
*/
constructor(opcode: Int, type: PacketType, buffer: ByteBuf) :
this(opcode, type, buffer, buffer.readableBytes())
/**
* If the packet is a raw packet
*/
fun isRaw() = opcode == 1
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment