Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,5 @@ protocol
examples/client_echo/client_echo
examples/client_verbose/client_verbose
examples/client_trivia/client_trivia

.idea/
3 changes: 3 additions & 0 deletions examples/client_trivia/bot/bot.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import (
"context"
"errors"
"fmt"
"io"
"log"
"log/slog"
"strconv"
"strings"
Expand Down Expand Up @@ -66,6 +68,7 @@ func (b *Bot) start(ctx context.Context, ip string, port int) error {
defer cancelCause(nil)

client := teeworlds7.NewClient()
client.Logger = log.New(io.Discard, "", 0) // an example on how to discard protocol debugging logs

client.OnUnknown(func(msg *messages7.Unknown, defaultAction teeworlds7.DefaultAction) error {
return nil
Expand Down
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,4 @@ module github.com/teeworlds-go/protocol

go 1.22.3

require github.com/teeworlds-go/huffman/v2 v2.0.0
require github.com/teeworlds-go/huffman/v2 v2.0.0
3 changes: 1 addition & 2 deletions object7/snap_object.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package object7

import (
"fmt"
"log"

"github.com/teeworlds-go/protocol/network7"
Expand Down Expand Up @@ -85,7 +84,7 @@ func NewObject(typeId int, itemId int, u *packer.Unpacker) SnapObject {
} else if typeId == network7.ObjGameDataRace {
race := &GameDataRace{ItemId: itemId}
size := u.GetInt()
fmt.Printf("got gamedata race red size=%d remaining unpacker data=%x\n", size, u.RemainingData())
//fmt.Printf("got gamedata race red size=%d remaining unpacker data=%x\n", size, u.RemainingData())
if size != race.Size() {
log.Panicf("got game data race with size %d but expected size %d\n", size, race.Size())
}
Expand Down
3 changes: 2 additions & 1 deletion snapshot7/ddnet_2part_snap_on_connect_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package snapshot7_test
// ddnet rus production server

import (
"log"
"testing"

"github.com/teeworlds-go/protocol/internal/testutils/require"
Expand Down Expand Up @@ -196,7 +197,7 @@ func TestDdnetCrash(t *testing.T) {
u := &packer.Unpacker{}
u.Reset(client.SnapshotStorage.IncomingData())

newFullSnap, err := snapshot7.UnpackDelta(prevSnap, u)
newFullSnap, err := snapshot7.UnpackDelta(log.Default(), prevSnap, u)
require.NoError(t, err)

err = client.SnapshotStorage.Add(part1.GameTick, newFullSnap)
Expand Down
3 changes: 2 additions & 1 deletion snapshot7/multi_part_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package snapshot7_test

import (
"log"
"testing"

"github.com/teeworlds-go/protocol/internal/testutils/require"
Expand Down Expand Up @@ -367,7 +368,7 @@ func Test4PartSnap(t *testing.T) {
u := &packer.Unpacker{}
u.Reset(client.SnapshotStorage.IncomingData())

newFullSnap, err := snapshot7.UnpackDelta(prevSnap, u)
newFullSnap, err := snapshot7.UnpackDelta(log.Default(), prevSnap, u)
require.NoError(t, err)

err = client.SnapshotStorage.Add(part2.GameTick, newFullSnap)
Expand Down
11 changes: 6 additions & 5 deletions snapshot7/snapshot7.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package snapshot7

import (
"fmt"
"log"
"log/slog"

"github.com/teeworlds-go/protocol/network7"
Expand Down Expand Up @@ -143,7 +144,7 @@ func (snap *Snapshot) GetItemIndex(key int) (index int, found bool) {
// it returns the new full snapshot with the delta applied to the from
//
// See also (Snapshot *)Unpack()
func UnpackDelta(from *Snapshot, u *packer.Unpacker) (*Snapshot, error) {
func UnpackDelta(l *log.Logger, from *Snapshot, u *packer.Unpacker) (*Snapshot, error) {
// TODO: add all the error checking the C++ reference implementation has

snap := &Snapshot{}
Expand All @@ -152,12 +153,12 @@ func UnpackDelta(from *Snapshot, u *packer.Unpacker) (*Snapshot, error) {
snap.NumItemDeltas = u.GetInt()
u.GetInt() // _zero

slog.Debug("got new snapshot!", "num_deleted", snap.NumRemovedItems, "num_updates", snap.NumItemDeltas)
l.Println("got new snapshot!", "num_deleted", snap.NumRemovedItems, "num_updates", snap.NumItemDeltas)

deletedKeys := make([]int, snap.NumRemovedItems)
for d := 0; d < snap.NumRemovedItems; d++ {
deletedKeys[d] = u.GetInt()
slog.Debug("delta unpack del key", "key", deletedKeys[d], "d_index", d, "num_deleted", snap.NumRemovedItems, "remaining_data", u.RemainingData())
l.Println("delta unpack del key", "key", deletedKeys[d], "d_index", d, "num_deleted", snap.NumRemovedItems, "remaining_data", u.RemainingData())
}

for i := 0; i < len(from.Items); i++ {
Expand All @@ -166,7 +167,7 @@ func UnpackDelta(from *Snapshot, u *packer.Unpacker) (*Snapshot, error) {

for _, deletedKey := range deletedKeys {
if deletedKey == ItemKey(fromItem) {
slog.Debug("delta del item", "deleted_key", deletedKey, "item_type", fromItem.TypeId(), "item_id", fromItem.Id())
l.Println("delta del item", "deleted_key", deletedKey, "item_type", fromItem.TypeId(), "item_id", fromItem.Id())
keep = false
break
}
Expand All @@ -181,7 +182,7 @@ func UnpackDelta(from *Snapshot, u *packer.Unpacker) (*Snapshot, error) {
itemType := u.GetInt()
itemId := u.GetInt()

slog.Debug("unpack item snap item ", "num", i, "total", snap.NumItemDeltas, "type", itemType, "id", itemId)
l.Println("unpack item snap item ", "num", i, "total", snap.NumItemDeltas, "type", itemType, "id", itemId)

item := object7.NewObject(itemType, itemId, u)
err := item.Unpack(u)
Expand Down
4 changes: 4 additions & 0 deletions teeworlds7/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package teeworlds7
import (
"context"
"fmt"
"log"
"net"
"time"

Expand Down Expand Up @@ -66,6 +67,8 @@ type Client struct {
// of the OnDisconnect callback
Ctx context.Context
CancelCause context.CancelCauseFunc

Logger *log.Logger
}

// TODO: add this for all items and move it to a different file
Expand Down Expand Up @@ -100,6 +103,7 @@ func NewClient() *Client {
},
LocalClientId: UnknownClientId,
LastSend: time.Now(),
Logger: log.Default(),
}
}

Expand Down
18 changes: 9 additions & 9 deletions teeworlds7/game.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,23 +19,23 @@ func (client *Client) processGame(netMsg messages7.NetMessage, response *protoco
case *messages7.SvMotd:
err = userMsgCallback(client.Callbacks.GameSvMotd, msg, func() error {
if msg.Message != "" {
fmt.Printf("[motd] %s\n", msg.Message)
client.Logger.Printf("[motd] %s\n", msg.Message)
}
return nil
})
case *messages7.SvBroadcast:
err = userMsgCallback(client.Callbacks.GameSvBroadcast, msg, func() error {
fmt.Printf("[broadcast] %s\n", msg.Message)
client.Logger.Printf("[broadcast] %s\n", msg.Message)
return nil
})
case *messages7.SvChat:
err = userMsgCallback(client.Callbacks.GameSvChat, msg, func() error {
if msg.ClientId < 0 || msg.ClientId > network7.MaxClients {
fmt.Printf("[chat] *** %s\n", msg.Message)
client.Logger.Printf("[chat] *** %s\n", msg.Message)
return nil
}
name := client.Game.Players[msg.ClientId].Info.Name
fmt.Printf("[chat] <%s> %s\n", name, msg.Message)
client.Logger.Printf("[chat] <%s> %s\n", name, msg.Message)
return nil
})
case *messages7.SvClientInfo:
Expand All @@ -44,24 +44,24 @@ func (client *Client) processGame(netMsg messages7.NetMessage, response *protoco
if msg.Local {
client.LocalClientId = msg.ClientId
}
fmt.Printf("got client info id=%d name=%s\n", msg.ClientId, msg.Name)
client.Logger.Printf("got client info id=%d name=%s\n", msg.ClientId, msg.Name)
return nil
})
case *messages7.SvReadyToEnter:
err = userMsgCallback(client.Callbacks.GameSvReadyToEnter, msg, func() error {
fmt.Println("got ready to enter")
client.Logger.Println("got ready to enter")
response.Messages = append(response.Messages, &messages7.EnterGame{})
return nil
})
case *messages7.Unknown:
err = userMsgCallback(client.Callbacks.MsgUnknown, msg, func() error {
// TODO: msg id of unknown messages should not be -1
fmt.Println("TODO: why is the msg id -1???")
printUnknownMessage(msg, "unknown game")
client.Logger.Println("TODO: why is the msg id -1???")
printUnknownMessage(client.Logger, msg, "unknown game")
return nil
})
default:
printUnknownMessage(netMsg, "unprocessed game")
printUnknownMessage(client.Logger, netMsg, "unprocessed game")
return false, nil
}
if err != nil {
Expand Down
33 changes: 17 additions & 16 deletions teeworlds7/packet.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package teeworlds7

import (
"fmt"
"log"

"github.com/teeworlds-go/protocol/messages7"
"github.com/teeworlds-go/protocol/network7"
Expand All @@ -20,23 +21,23 @@ func (e DisconnectError) Error() string {
return fmt.Sprintf("disconnected: %s", e.Reason)
}

func printUnknownMessage(msg messages7.NetMessage, msgType string) {
fmt.Printf("%s message id=%d\n", msgType, msg.MsgId())
func printUnknownMessage(l *log.Logger, msg messages7.NetMessage, msgType string) {
l.Printf("%s message id=%d\n", msgType, msg.MsgId())
if msg.Header() == nil {
fmt.Println(" header: nil")
l.Println(" header: nil")
} else {
fmt.Printf(" header: %x\n", msg.Header().Pack())
l.Printf(" header: %x\n", msg.Header().Pack())
}
fmt.Printf(" payload: %x\n", msg.Pack())
l.Printf(" payload: %x\n", msg.Pack())
if msg.Header() != nil {
fmt.Printf(" full msg: %x%x\n", msg.Header().Pack(), msg.Pack())
l.Printf(" full msg: %x%x\n", msg.Header().Pack(), msg.Pack())
}
}

func (client *Client) processMessage(msg messages7.NetMessage, response *protocol7.Packet) (process bool, err error) {
func (client *Client) processMessage(l *log.Logger, msg messages7.NetMessage, response *protocol7.Packet) (process bool, err error) {
if msg.Header() == nil {
// this is probably an unknown message
fmt.Printf("warning ignoring msgId=%d because header is nil\n", msg.MsgId())
l.Printf("warning ignoring msgId=%d because header is nil\n", msg.MsgId())
return false, nil
}
if msg.Header().Flags.Vital {
Expand Down Expand Up @@ -75,18 +76,18 @@ func (client *Client) processPacket(packet *protocol7.Packet) (err error) {
switch msg := msg.(type) {
case *messages7.CtrlKeepAlive:
err = userMsgCallback(client.Callbacks.CtrlKeepAlive, msg, func() error {
fmt.Println("got keep alive")
client.Logger.Println("got keep alive")
return nil
})
case *messages7.CtrlConnect:
err = userMsgCallback(client.Callbacks.CtrlConnect, msg, func() error {
fmt.Println("we got connect as a client. this should never happen lol.")
fmt.Println("who is trying to connect to us? We are not a server!")
client.Logger.Println("we got connect as a client. this should never happen lol.")
client.Logger.Println("who is trying to connect to us? We are not a server!")
return nil
})
case *messages7.CtrlAccept:
err = userMsgCallback(client.Callbacks.CtrlAccept, msg, func() error {
fmt.Println("got accept")
client.Logger.Println("got accept")
response.Messages = append(
response.Messages,
&messages7.Info{
Expand All @@ -100,12 +101,12 @@ func (client *Client) processPacket(packet *protocol7.Packet) (err error) {
case *messages7.CtrlClose:
err = userMsgCallback(client.Callbacks.CtrlClose, msg, func() error {
client.CancelCause(DisconnectError{Reason: msg.Reason})
fmt.Printf("disconnected (%s)\n", msg.Reason)
client.Logger.Printf("disconnected (%s)\n", msg.Reason)
return nil
})
case *messages7.CtrlToken:
err = userMsgCallback(client.Callbacks.CtrlToken, msg, func() error {
fmt.Printf("got server token %x\n", msg.Token)
client.Logger.Printf("got server token %x\n", msg.Token)
client.Session.ServerToken = msg.Token
response.Header.Token = msg.Token
response.Messages = append(
Expand All @@ -118,7 +119,7 @@ func (client *Client) processPacket(packet *protocol7.Packet) (err error) {
})
case *messages7.Unknown:
err = userMsgCallback(client.Callbacks.MsgUnknown, msg, func() error {
printUnknownMessage(msg, "unknown control")
printUnknownMessage(client.Logger, msg, "unknown control")
return nil
})
if err != nil {
Expand All @@ -133,7 +134,7 @@ func (client *Client) processPacket(packet *protocol7.Packet) (err error) {
}

for _, msg := range packet.Messages {
_, err = client.processMessage(msg, response)
_, err = client.processMessage(client.Logger, msg, response)
if err != nil {
return err
}
Expand Down
Loading
Loading