semi synced multiplayer
This commit is contained in:
+25
-10
@@ -10,14 +10,22 @@ import (
|
||||
)
|
||||
|
||||
const (
|
||||
MsgKeyPress uint16 = 1
|
||||
MsgGameState uint16 = 2
|
||||
MSGServerStatus uint16 = 3
|
||||
MSGOnConnect uint16 = 4
|
||||
MsgKeyPress uint16 = 1
|
||||
MsgGameState uint16 = 2
|
||||
MSGServerStatus uint16 = 3
|
||||
MSGOnConnect uint16 = 4
|
||||
MSGOnPlayerConnect uint16 = 5
|
||||
)
|
||||
|
||||
var num_clients int = 0
|
||||
var clients = map[int]net.Conn{}
|
||||
var clients = make(map[string]client)
|
||||
|
||||
type client struct {
|
||||
x uint
|
||||
y uint
|
||||
client_id string
|
||||
conn net.Conn
|
||||
}
|
||||
|
||||
func Start() {
|
||||
listener, err := net.Listen("tcp", ":9000")
|
||||
@@ -34,18 +42,25 @@ func Start() {
|
||||
continue
|
||||
}
|
||||
|
||||
// client connects
|
||||
num_clients += 1
|
||||
client_id := strconv.Itoa(num_clients)
|
||||
fmt.Println(client_id)
|
||||
go SendPacket(MSGOnConnect, []byte(client_id))
|
||||
addClient(conn, num_clients)
|
||||
go SendPacket(MSGOnPlayerConnect, []byte(client_id))
|
||||
|
||||
addClient(conn, client_id)
|
||||
|
||||
go handle(conn)
|
||||
}
|
||||
}
|
||||
|
||||
func addClient(conn net.Conn, id int) {
|
||||
clients[id] = conn
|
||||
func addClient(conn net.Conn, id string) {
|
||||
var new_client client = client{
|
||||
client_id: id,
|
||||
conn: conn,
|
||||
}
|
||||
clients[id] = new_client
|
||||
}
|
||||
|
||||
func SendPacket(msgID uint16, payload []byte) error {
|
||||
@@ -57,8 +72,8 @@ func SendPacket(msgID uint16, payload []byte) error {
|
||||
binary.BigEndian.PutUint16(buf[4:6], msgID)
|
||||
copy(buf[6:], payload)
|
||||
|
||||
for _, conn := range clients {
|
||||
n, err := conn.Write(buf)
|
||||
for _, client := range clients {
|
||||
n, err := client.conn.Write(buf)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user