Implement inital handshake and receive loop

This commit is contained in:
2026-05-22 14:56:16 +02:00
parent c5a875be34
commit 1b8d01735c

View File

@@ -19,6 +19,8 @@ type PacketEngine struct {
Ready bool Ready bool
conn net.Conn conn net.Conn
mu sync.Mutex mu sync.Mutex
Messages chan []byte
version string
} }
func WithTimeout(d time.Duration) Option { func WithTimeout(d time.Duration) Option {
@@ -27,7 +29,7 @@ func WithTimeout(d time.Duration) Option {
} }
} }
func NewPacketEngine(address string, opts ...Option) (*PacketEngine, error) { func NewPacketEngine(address string, opts ...Option) *PacketEngine {
defaultCfg := Config{ defaultCfg := Config{
Timeout: 5 * time.Second, Timeout: 5 * time.Second,
} }
@@ -36,11 +38,14 @@ func NewPacketEngine(address string, opts ...Option) (*PacketEngine, error) {
opt(&defaultCfg) opt(&defaultCfg)
} }
return &PacketEngine{ pe := PacketEngine{
address: address, address: address,
cfg: defaultCfg, cfg: defaultCfg,
Ready: false, Ready: false,
}, nil Messages: make(chan []byte),
}
return &pe
} }
func (pe *PacketEngine) Connect() error { func (pe *PacketEngine) Connect() error {
@@ -50,6 +55,7 @@ func (pe *PacketEngine) Connect() error {
} }
pe.conn = conn pe.conn = conn
fmt.Println("Connected to", pe.address) fmt.Println("Connected to", pe.address)
go pe.receiveLoop()
return nil return nil
} }
@@ -64,3 +70,37 @@ func (pe *PacketEngine) Disconnect() error {
return nil return nil
} }
func (pe *PacketEngine) Send(data []byte) error {
_, err := pe.conn.Write(data)
return err
}
func (pe *PacketEngine) receiveLoop() {
defer close(pe.Messages)
for {
buf := make([]byte, 1024)
n, err := pe.conn.Read(buf)
if err != nil {
// FIXME: handle error
panic(err)
}
data := buf[:n]
pe.Messages <- data
}
}
func (pe *PacketEngine) Version() string {
if pe.conn == nil {
return ""
}
if pe.version != "" {
return pe.version
}
return fmt.Sprintf("%d.%d")
}