-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.go
172 lines (156 loc) · 3.94 KB
/
server.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
package main
import (
"errors"
"fmt"
"github.com/go-logr/logr"
"github.com/go-logr/stdr"
"log"
"net"
"os"
"sync"
)
const (
handshake = iota + 1
handshakeResponse
position
positionResponse
)
func check(err error) {
if err != nil {
panic(err)
}
}
type coords struct {
x, y uint8
}
type state struct {
*sync.Mutex
positions map[uint8]coords
}
type server struct {
conn *net.UDPConn
state *state
log logr.Logger
}
func (s *state) setPosition(id, x, y uint8) {
s.Lock()
s.positions[id] = coords{x, y}
s.Unlock()
}
type message struct {
opcode uint8
data []byte
}
func (m message) encode() []byte {
payload := make([]byte, 0, len(m.data)+1) // +1 for opcode
payload = append(payload, m.opcode)
payload = append(payload, m.data...)
return payload
}
func decode(payload []byte) (message, error) {
if len(payload) < 2 {
return message{}, errors.New("payload too short")
}
return message{
opcode: payload[0],
data: payload[1:],
}, nil
}
//func (s *server) notifyPeriodically(remote *net.UDPAddr) {
// response := message{}
// _, err := s.conn.WriteToUDP(response.encode(), remote)
// if err != nil {
// s.log.Error(err, "periodic notification failed", "remote", remote)
// return
// }
//}
func (s *server) handleHandshake(m message, remote *net.UDPAddr) {
s.log.V(5).Info("opcode = handshake", "data", fmt.Sprintf("%x", m.data))
playerId := m.data[0]
s.state.Lock()
_, present := s.state.positions[playerId]
s.state.Unlock()
if present {
s.log.Error(nil, "player is already present", "player ID", playerId)
return
}
s.state.setPosition(playerId, 0, 0)
response := message{handshakeResponse, []byte{playerId}}
_, err := s.conn.WriteToUDP(response.encode(), remote)
if err != nil {
s.log.Error(err, "response failed")
return
}
s.log.V(5).Info("handshake response sent", "data", fmt.Sprintf("%x", response.data), "to", remote)
}
func (s *server) handlePosition(m message, remote *net.UDPAddr) {
s.log.V(5).Info("opcode = position", "data", fmt.Sprintf("%x", m.data))
if len(m.data) < 3 {
s.log.Error(nil, "data too short in position packet", "opcode", fmt.Sprintf("%x", m.opcode), "data", fmt.Sprintf("%x", m.data))
return
}
playerId := m.data[0]
x := m.data[1]
y := m.data[2]
s.state.setPosition(playerId, x, y)
s.state.Lock()
positionsData := make([]byte, 0, len(s.state.positions))
positionsData = append(positionsData, byte(len(s.state.positions)-1))
for k, v := range s.state.positions {
if k != playerId {
positionsData = append(positionsData, k, v.x, v.y)
s.log.V(10).Info("position data", "player", k, "x", v.x, "y", v.y)
}
}
s.state.Unlock()
response := message{positionResponse, positionsData}
_, err := s.conn.WriteToUDP(response.encode(), remote)
if err != nil {
s.log.Error(err, "response failed")
return
}
s.log.V(5).Info("response sent", "data", fmt.Sprintf("%x", response.data), "to", remote)
}
func (s *server) handle(m message, remote *net.UDPAddr) {
s.log.V(5).Info("received message", "opcode", fmt.Sprintf("%x", m.opcode), "from", remote)
switch m.opcode {
case handshake:
s.handleHandshake(m, remote)
case position:
s.handlePosition(m, remote)
default:
s.log.Error(nil, "unknown opcode")
}
}
func main() {
stdr.SetVerbosity(10)
conn, err := net.ListenUDP("udp", &net.UDPAddr{
IP: net.ParseIP("0.0.0.0"),
Port: 25565,
})
check(err)
defer conn.Close()
server := server{
conn: conn,
state: &state{
Mutex: &sync.Mutex{},
positions: make(map[uint8]coords),
},
log: stdr.New(log.New(os.Stderr, "", log.LstdFlags|log.Lshortfile)),
}
server.log.V(0).Info("server listening", "address", conn.LocalAddr().String())
for {
buffer := make([]byte, 32)
receivedLen, remote, err := conn.ReadFromUDP(buffer)
if err != nil {
server.log.Error(err, "UDP packet dropped due to error")
continue
}
m, err := decode(buffer[:receivedLen])
if err != nil {
server.log.Error(err, "UDP packet dropped due to error")
continue
}
go server.handle(m, remote)
}
}