This commit is contained in:
harper
2026-07-09 20:43:41 -07:00
parent bc14e946fc
commit c5cb04d760
5 changed files with 168 additions and 16 deletions
+26 -13
View File
@@ -6,13 +6,19 @@ import (
"io"
"log"
"net"
"strconv"
)
const (
MsgKeyPress uint16 = 1
MsgGameState uint16 = 2
MSGServerStatus uint16 = 3
MSGOnConnect uint16 = 4
)
var num_clients int = 0
var clients = map[int]net.Conn{}
func Start() {
listener, err := net.Listen("tcp", ":9000")
if err != nil {
@@ -28,13 +34,21 @@ func Start() {
continue
}
fmt.Println("Client connected")
num_clients += 1
client_id := strconv.Itoa(num_clients)
fmt.Println(client_id)
go SendPacket(MSGOnConnect, []byte(client_id))
addClient(conn, num_clients)
go handle(conn)
}
}
func SendPacket(conn net.Conn, msgID uint16, payload []byte) error {
func addClient(conn net.Conn, id int) {
clients[id] = conn
}
func SendPacket(msgID uint16, payload []byte) error {
// Length matches Lua: 2 (msgID) + payload size
length := uint32(2 + len(payload))
buf := make([]byte, 4+2+len(payload))
@@ -43,12 +57,14 @@ func SendPacket(conn net.Conn, msgID uint16, payload []byte) error {
binary.BigEndian.PutUint16(buf[4:6], msgID)
copy(buf[6:], payload)
n, err := conn.Write(buf)
if err != nil {
return err
}
if n != len(buf) {
return fmt.Errorf("short write: expected %d bytes, got %d", len(buf), n)
for _, conn := range clients {
n, err := conn.Write(buf)
if err != nil {
return err
}
if n != len(buf) {
return fmt.Errorf("short write: expected %d bytes, got %d", len(buf), n)
}
}
return nil
}
@@ -67,6 +83,7 @@ func handle(conn net.Conn) {
}
fmt.Println("Client disconnected")
num_clients -= 1
return
}
@@ -102,11 +119,7 @@ func handle(conn net.Conn) {
fmt.Println(msg)
// Send something back to the client
err := SendPacket(conn, MsgGameState, []byte("received key press: "+msg))
if err != nil {
fmt.Println("Send error:", err)
return
}
go SendPacket(MsgGameState, []byte(msg))
default:
fmt.Println("Unknown message:", msgID)