add packet buffer pool for connection

This commit is contained in:
Tnze
2023-06-23 10:26:35 +08:00
parent f919d93544
commit a2cae2b77b
2 changed files with 9 additions and 2 deletions

View File

@ -2,6 +2,7 @@ package bot
import (
"errors"
"sync"
"github.com/google/uuid"
@ -46,6 +47,7 @@ func NewClient() *Client {
type Conn struct {
*net.Conn
send, recv queue.Queue[pk.Packet]
pool sync.Pool // pool of recv packet data
rerr error
}
@ -54,11 +56,13 @@ func warpConn(c *net.Conn, qr, qw queue.Queue[pk.Packet]) *Conn {
Conn: c,
send: qw,
recv: qr,
pool: sync.Pool{New: func() any { return []byte{} }},
rerr: nil,
}
go func() {
for {
var p pk.Packet
// take a buffer from pool, after the packet is handled we put it back
p := pk.Packet{Data: wc.pool.Get().([]byte)}
if err := c.ReadPacket(&p); err != nil {
wc.rerr = err
break

View File

@ -10,8 +10,8 @@ import (
// HandleGame receive server packet and response them correctly.
// Note that HandleGame will block if you don't receive from Events.
func (c *Client) HandleGame() error {
var p pk.Packet
for {
var p pk.Packet
// Read packets
if err := c.Conn.ReadPacket(&p); err != nil {
return err
@ -22,6 +22,9 @@ func (c *Client) HandleGame() error {
if err != nil {
return err
}
// return the packet buffer
c.Conn.pool.Put(p.Data)
}
}