go-teeworlds-protocol/teeworlds.go

83 lines
1.4 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"
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},
Conn: conn,
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, client.Conn)
2024-06-01 03:01:48 +00:00
2024-06-20 03:08:52 +00:00
packet := client.CtrlToken()
conn.Write(packet.Pack(client))
2024-06-01 02:34:53 +00:00
for {
time.Sleep(10_000_000)
select {
case msg := <-ch:
2024-06-20 03:08:52 +00:00
packet, err = client.OnPacket(msg)
if err != nil {
panic(err)
}
if packet != nil {
conn.Write(packet.Pack(client))
}
2024-06-01 02:34:53 +00:00
default:
// do nothing
}
}
}