go-teeworlds-protocol/teeworlds.go

95 lines
1.8 KiB
Go
Raw Normal View History

2024-06-02 02:58:09 +00:00
package main
2024-06-01 02:34:53 +00:00
import (
"bufio"
"fmt"
"net"
2024-06-01 03:01:48 +00:00
"os"
2024-06-01 02:34:53 +00:00
"time"
"github.com/teeworlds-go/teeworlds/messages7"
2024-06-19 04:57:32 +00:00
"github.com/teeworlds-go/teeworlds/network7"
"github.com/teeworlds-go/teeworlds/protocol7"
2024-06-01 02:34:53 +00:00
)
const (
2024-06-01 03:45:32 +00:00
maxPacksize = 1400
2024-06-01 02:34:53 +00:00
)
2024-06-01 03:01:48 +00:00
func getConnection() (net.Conn, error) {
2024-06-01 02:34:53 +00:00
conn, err := net.Dial("udp", "127.0.0.1:8303")
if err != nil {
fmt.Printf("Some error %v", err)
}
2024-06-01 03:01:48 +00:00
return conn, err
}
2024-06-01 02:34:53 +00:00
func readNetwork(ch chan<- []byte, conn net.Conn) {
buf := make([]byte, maxPacksize)
2024-06-01 02:34:53 +00:00
for {
len, err := bufio.NewReader(conn).Read(buf)
packet := make([]byte, len)
copy(packet[:], buf[:])
2024-06-01 02:34:53 +00:00
if err == nil {
ch <- packet
} else {
fmt.Printf("Some error %v\n", err)
break
}
}
conn.Close()
}
func main() {
ch := make(chan []byte, maxPacksize)
2024-06-01 03:01:48 +00:00
conn, err := getConnection()
if err != nil {
fmt.Printf("error connecting %v\n", err)
os.Exit(1)
}
client := &protocol7.Connection{
ClientToken: [4]byte{0x01, 0x02, 0x03, 0x04},
ServerToken: [4]byte{0xff, 0xff, 0xff, 0xff},
2024-06-18 05:08:56 +00:00
Ack: 0,
2024-06-19 04:57:32 +00:00
Players: make([]protocol7.Player, network7.MaxClients),
2024-06-01 03:45:32 +00:00
}
go readNetwork(ch, conn)
2024-06-01 03:01:48 +00:00
2024-06-20 04:29:26 +00:00
tokenPacket := client.CtrlToken()
conn.Write(tokenPacket.Pack(client))
2024-06-01 02:34:53 +00:00
for {
time.Sleep(10_000_000)
select {
case msg := <-ch:
2024-06-20 04:29:26 +00:00
result, err := client.OnPacket(msg)
2024-06-20 03:08:52 +00:00
if err != nil {
panic(err)
}
2024-06-20 04:29:26 +00:00
if result.Response != nil {
// example of modifying outgoing traffic
2024-06-20 04:29:26 +00:00
for i, msg := range result.Response.Messages {
if msg.MsgId() == network7.MsgCtrlConnect {
var connect *messages7.CtrlConnect
var ok bool
if connect, ok = result.Response.Messages[0].(*messages7.CtrlConnect); ok {
connect.Token = [4]byte{0xaa, 0xaa, 0xaa, 0xaa}
2024-06-20 04:29:26 +00:00
result.Response.Messages[i] = connect
}
}
}
2024-06-20 04:29:26 +00:00
conn.Write(result.Response.Pack(client))
2024-06-20 03:08:52 +00:00
}
2024-06-01 02:34:53 +00:00
default:
// do nothing
}
}
}