I'm trying to write a game server and need to create the packet I'll be sending back to the client. I am writing all the data into a bytes.Buffer
then I want to prefix the total size of the packet before getting the bytes and sending it to the client.
I was thinking of something like this:
// is it bad to call `var b bytes.Buffer` every time I create a packet?
func CreatePacket() []byte {
var b bytes.Buffer
// size
binary.Write(b, binary.LittleEndian, 0) // insert at end
// body (variable number of writes)
binary.Write(b, binary.LittleEndian, data)
// update the size at offset 0
binary.Write(b, binary.LittleEndian, b.Len())
return b.Bytes()
}
But I can't find any method to seek or modify the offset.
This doesn't work, why?
var packet = b.Bytes()
// the size is really at offset 2. offset 0 is an ID.
binary.LittleEndian.PutUint16(packet, uint16(0xF3))
binary.LittleEndian.PutUint16(packet, uint16(len(packet)))
You can write the length directly to the slice after you have assembled the packet. You will also want to specify the length prefix size so that it is identical across platforms.
func CreatePacket(data []byte) []byte {
// leave 4 bytes at the start for the ID and length
b := bytes.NewBuffer(make([]byte, 4))
binary.Write(b, binary.LittleEndian, data)
packet := b.Bytes()
// insert the ID and prefix
binary.LittleEndian.PutUint16(packet, uint16(0xF3))
binary.LittleEndian.PutUint16(packet[2:], uint16(len(packet)))
return packet
}