forked from rbxb/place
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
230 lines (210 loc) · 4.46 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
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
package place
import (
"bytes"
"encoding/binary"
"errors"
"fmt"
"image/color"
"image/draw"
"image/png"
"log"
"net/http"
"path"
"strconv"
"sync"
"time"
"github.com/gorilla/websocket"
)
var upgrader = websocket.Upgrader{
ReadBufferSize: 64,
WriteBufferSize: 64,
CheckOrigin: func(r *http.Request) bool {
return true
},
Error: func(w http.ResponseWriter, req *http.Request, status int, err error) {
log.Println(err)
http.Error(w, "Error while trying to make websocket connection.", status)
},
}
type Server struct {
sync.RWMutex
msgs chan []byte
close chan int
clients []chan []byte
img draw.Image
imgBuf []byte
}
func NewServer(img draw.Image, count int) *Server {
sv := &Server{
RWMutex: sync.RWMutex{},
msgs: make(chan []byte),
close: make(chan int),
clients: make([]chan []byte, count),
img: img,
}
go sv.broadcastLoop()
return sv
}
func (sv *Server) ServeHTTP(w http.ResponseWriter, req *http.Request) {
switch path.Base(req.URL.Path) {
case "place.png":
sv.HandleGetImage(w, req)
case "stat":
sv.HandleGetStat(w, req)
case "ws":
sv.HandleSocket(w, req)
default:
http.Error(w, "Not found.", 404)
}
}
func (sv *Server) HandleGetImage(w http.ResponseWriter, req *http.Request) {
b := sv.GetImageBytes() //not thread safe but it won't do anything bad
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Content-Length", strconv.Itoa(len(b)))
w.Header().Set("Cache-Control", "no-cache, no-store")
w.Write(b)
}
func (sv *Server) HandleGetStat(w http.ResponseWriter, req *http.Request) {
count := 0
for _, ch := range sv.clients {
if ch != nil {
count++
}
}
fmt.Fprint(w, count)
}
func (sv *Server) HandleSocket(w http.ResponseWriter, req *http.Request) {
sv.Lock()
defer sv.Unlock()
i := sv.getConnIndex()
if i == -1 {
log.Println("Server full.")
http.Error(w, "Server full.", 503)
return
}
conn, err := upgrader.Upgrade(w, req, nil)
if err != nil {
log.Println(err)
return
}
ch := make(chan []byte, 8)
sv.clients[i] = ch
go sv.readLoop(conn, i)
go sv.writeLoop(conn, ch)
}
func (sv *Server) getConnIndex() int {
for i, client := range sv.clients {
if client == nil {
return i
}
}
return -1
}
func rateLimiter() func() bool {
const rate = 8 // per second average
const min = 0.01 // kick threshold
// Minimum time difference between messages
// Network sometimes delivers two messages in quick succession
const minDif = int64(time.Millisecond * 50)
last := time.Now().UnixNano()
var v float32 = 1.0
return func() bool {
now := time.Now().UnixNano()
dif := now - last
if dif < minDif {
dif = minDif
}
v *= float32(rate*dif) / float32(time.Second)
if v > 1.0 {
v = 1.0
}
last = now
return v > min
}
}
func (sv *Server) readLoop(conn *websocket.Conn, i int) {
limiter := rateLimiter()
for {
_, p, err := conn.ReadMessage()
if err != nil {
break
}
if !limiter() {
log.Println("Client kicked for high rate.")
break
}
if sv.handleMessage(p) != nil {
log.Println("Client kicked for bad message.")
break
}
}
sv.close <- i
}
func (sv *Server) writeLoop(conn *websocket.Conn, ch chan []byte) {
for {
if p, ok := <-ch; ok {
conn.WriteMessage(websocket.BinaryMessage, p)
} else {
break
}
}
conn.Close()
}
func (sv *Server) handleMessage(p []byte) error {
if !sv.setPixel(parseEvent(p)) {
return errors.New("invalid placement")
}
sv.msgs <- p
return nil
}
func (sv *Server) broadcastLoop() {
for {
select {
case i := <-sv.close:
if sv.clients[i] != nil {
close(sv.clients[i])
sv.clients[i] = nil
}
case p := <-sv.msgs:
for i, ch := range sv.clients {
if ch != nil {
select {
case ch <- p:
default:
close(ch)
sv.clients[i] = nil
}
}
}
}
}
}
func (sv *Server) GetImageBytes() []byte {
if sv.imgBuf == nil {
buf := bytes.NewBuffer(nil)
if err := png.Encode(buf, sv.img); err != nil {
log.Println(err)
}
sv.imgBuf = buf.Bytes()
}
return sv.imgBuf
}
func (sv *Server) setPixel(x, y int, c color.Color) bool {
rect := sv.img.Bounds()
width := rect.Max.X - rect.Min.X
height := rect.Max.Y - rect.Min.Y
if 0 > x || x >= width || 0 > y || y >= height {
return false
}
sv.img.Set(x, y, c)
sv.imgBuf = nil
return true
}
func parseEvent(b []byte) (int, int, color.Color) {
if len(b) != 11 {
return -1, -1, nil
}
x := int(binary.BigEndian.Uint32(b))
y := int(binary.BigEndian.Uint32(b[4:]))
return x, y, color.NRGBA{b[8], b[9], b[10], 0xFF}
}