-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
437 lines (426 loc) · 12 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
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
package main
import (
"encoding/json"
"fmt"
"io"
"net"
"net/http"
"strconv"
"sync"
"text/template"
"time"
)
/* bind port for UDP socket
* 'message' data use Message struct protocol and relayUDP function
* others use raw data package protocol and relayUDPRaw function
*/
var UDPPortsDict = map[string]int{
"sensor":10002,
"cmd":10003,
"debug":10004,
"clock":10005,
"message":10006,
}
/* bind port for TCP socket
* 'vision' data use raw image encode data protocol and relayTCPRaw function
*/
var TCPPortsDict = map[string]int{
"vision":10001,
}
// communication protocol for register information and 'message' data
type Message struct {
Mtype string
Pri int
Id string
Data string
}
// Thread-safe maps
/*
* clientUDPIPs ---> key: robotId, value: ip(string)
* clientUDPPorts ---> key: robotID:dataKey(string), value: ip(int)
* clientUDPSockets ---> key: dataKey(string), value: socket(*net.UDPConn)
* clientUDPSockets will be established at the beginning
*/
var clientUDPIPs, clientUDPPorts, clientUDPSockets sync.Map
/*
* clientTCPIPs ---> key: robotId, value: ip(string)
* clientTCPPorts ---> key: robotID:dataKey(string), value: ip(int)
* clientTCPSockets ---> key: IP:port(string), value: socket(net.Conn)
*/
var clientTCPIPs, clientTCPPorts, clientTCPSockets sync.Map
/* FPS counters, they will be cleared every second by FPSCounter function
* UDPRecvCnt, UDPRelayCnt ---> key: robotID:dataKey(string)
* TCPRecvCnt, TCPRelayCnt ---> key: IP:port(string)
*/
var UDPRecvCnt, TCPRecvCnt, UDPRelayCnt, TCPRelayCnt sync.Map
/* store TCP and UDP connection information
* UDPStateMap ---> key: robotID:dataKey(string), value: SocketState
* TCPStateMap ---> key: IP:port(string), value: SocketState
*/
var UDPStateMap, TCPStateMap sync.Map
// Block the main function
var done = make(chan struct{})
// web visualization information
type SocketState struct {
Key string
Type string
IP string
Port int
RecvFPS int
RelayFPS int
}
// index.html resource
var myTemplate *template.Template
// data for web HTML
var socketStates []SocketState
// slice is not thread-safe
var mutex sync.RWMutex
// check error, function just prints the error information
func checkErr(err error){
if err != nil {
fmt.Println(err)
}
}
// UDP step 1
func readUDP(socket *net.UDPConn, key string) {
for {
data := make([]byte, 65535)
n, remoteAddr, err := socket.ReadFromUDP(data)
checkErr(err)
ip, _port, err := net.SplitHostPort(remoteAddr.String())
port,err := strconv.Atoi(_port)
checkErr(err)
var message Message
err = json.Unmarshal(data[:n], &message)
if err != nil || message.Id == ""{
go relayUDPRaw(data, n, ip, port, key)
continue
}
if message.Mtype == "register" {
fmt.Printf("Register UDP <%s:%s> %s\n", key, message.Id, message.Data)
clientUDPIPs.Store(message.Id, ip)
clientUDPPorts.Store(message.Id+":"+key, port)
feedback := Message{
Mtype: "register",
Pri: 5,
Id: "000000",
Data: remoteAddr.String(),
}
feedbackStr, err := json.Marshal(feedback)
checkErr(err)
SocketState := SocketState{Key:key, Type:"UDP", IP: ip, Port: port, RecvFPS:0, RelayFPS:0}
UDPStateMap.Store(message.Id+":"+key, SocketState)
UDPRecvCnt.Store(message.Id+":"+key, 0)
UDPRelayCnt.Store(message.Id+":"+key, 0)
socket.WriteToUDP(feedbackStr, remoteAddr)
} else {
go relayUDP(data, n, message.Id, key)
}
}
}
// UDP step 2-1
func relayUDP(data []byte, n int, myID string, key string) {
cnt, _ := UDPRecvCnt.Load(myID+":"+key)
// check type for safety
switch cnt.(type) {
case int:
UDPRecvCnt.Store(myID+":"+key, cnt.(int)+1)
default:
UDPRecvCnt.Store(myID+":"+key, 0)
}
clientUDPIPs.Range(func(robotID, ip interface{})bool{
if robotID.(string) == myID {
return true
}
port, ok := clientUDPPorts.Load(robotID.(string)+":"+key)
if !ok{
fmt.Println("No UDP port in key", robotID.(string)+":"+key)
return true
}
clientAddr := &net.UDPAddr{IP: net.ParseIP(ip.(string)), Port: port.(int)}
socket, ok := clientUDPSockets.Load(key)
if !ok {
return true
}
socket.(*net.UDPConn).WriteToUDP(data[:n], clientAddr)
cnt, _ := UDPRelayCnt.Load(myID+":"+key)
// check type for safety
switch cnt.(type) {
case int:
UDPRelayCnt.Store(myID+":"+key, cnt.(int)+1)
default:
UDPRelayCnt.Store(myID+":"+key, 0)
}
return true
})
}
// UDP step 2-2
func relayUDPRaw(data []byte, n int, myIP string, myPort int, key string) {
var myID string
// find my ID
clientUDPIPs.Range(func(robotId,ip interface{})bool{
// get port
_port, ok := clientUDPPorts.Load(robotId.(string)+":"+key)
if !ok {
fmt.Println("No key in UDP port", robotId.(string)+":"+key)
return true
}
port := _port.(int)
// running on the same machine may have the same IP address
// running on different machines may have the same port
if myIP == ip.(string) && myPort == port{
myID = robotId.(string)
}
return true
})
// recv cnt ++
cnt, _ := UDPRecvCnt.Load(myID+":"+key)
// check type for safety
switch cnt.(type) {
case int:
UDPRecvCnt.Store(myID+":"+key, cnt.(int)+1)
default:
UDPRecvCnt.Store(myID+":"+key, 0)
}
clientUDPIPs.Range(func(robotId,ip interface{})bool{
// get port
_port, ok := clientUDPPorts.Load(robotId.(string)+":"+key)
if !ok {
fmt.Println("No key in UDP port", robotId.(string)+":"+key)
return true
}
port := _port.(int)
if myIP == ip.(string) && port == myPort {
return true
}
clientAddr := &net.UDPAddr{IP: net.ParseIP(ip.(string)), Port: port}
socket, ok := clientUDPSockets.Load(key)
if !ok {
return true
}
socket.(*net.UDPConn).WriteToUDP(data[:n], clientAddr)
// relay cnt ++
cnt, _ := UDPRelayCnt.Load(myID+":"+key)
// check type for safety
switch cnt.(type) {
case int:
UDPRelayCnt.Store(myID+":"+key, cnt.(int)+1)
default:
UDPRelayCnt.Store(myID+":"+key, 0)
}
return true
})
}
// TCP step 1
func readTCP(socket *net.TCPListener, key string){
for {
conn, err := socket.Accept()
fmt.Printf("Register TCP <%s> %s\n",conn.RemoteAddr().String(), key)
checkErr(err)
remoteAddr := conn.RemoteAddr()
ip, _port, err := net.SplitHostPort(remoteAddr.String())
port,err := strconv.Atoi(_port)
checkErr(err)
go handleTCP(conn, ip, port, remoteAddr, key)
}
}
// TCP step 2
func handleTCP(conn net.Conn, ip string, port int, remoteAddr net.Addr, key string){
defer conn.Close()
for {
data := make([]byte, 65535*5)
n, err := conn.Read(data)
if err == io.EOF || n == 0{
conn.Close()
conn = nil
break
}
var message Message
if err := json.Unmarshal(data[:n], &message); err != nil {
go relayTCPRaw(data, n, remoteAddr, key)
}
checkErr(err)
if message.Mtype == "register" {
//fmt.Printf("Register <%s:%s> %s\n", key, message.Id, message.Data)
clientTCPIPs.Store(message.Id, ip)
clientTCPPorts.Store(message.Id+":"+key, port)
feedback := Message{
Mtype: "register",
Pri: 5,
Id: "000000",
Data: remoteAddr.String(),
}
feedbackStr, err := json.Marshal(feedback)
checkErr(err)
_, err = conn.Write(feedbackStr)
checkErr(err)
SocketState := SocketState{Key:key, Type:"TCP", IP: ip, Port: port, RecvFPS:0, RelayFPS:0}
TCPStateMap.Store(remoteAddr.String(), SocketState)
clientTCPSockets.Store(remoteAddr.String(), conn)
TCPRecvCnt.Store(remoteAddr.String(), 0)
TCPRelayCnt.Store(remoteAddr.String(), 0)
} else {
go relayTCP(data, n, message.Id, key, ip, port)
}
}
fmt.Printf("Close TCP connection <%s:%d> as %s\n", ip, port, key)
}
// TCP step 3-1
func relayTCP(data []byte, n int, robotID string, key string, ip string, port int) {
cnt, _ := TCPRecvCnt.Load(ip+":"+strconv.Itoa(port))
// check type for safety
switch cnt.(type) {
case int:
TCPRecvCnt.Store(ip+":"+strconv.Itoa(port), cnt.(int)+1)
default:
TCPRecvCnt.Store(ip+":"+strconv.Itoa(port), 0)
}
clientTCPIPs.Range(func(otherID,value interface{})bool{
if otherID == robotID {
return true
}
conn, ok := clientTCPSockets.Load(otherID.(string)+":"+key)
if !ok {
return true
}
conn.(net.Conn).Write(data[:n])
cnt, _ := TCPRelayCnt.Load(ip+":"+strconv.Itoa(port))
// check type for safety
switch cnt.(type) {
case int:
TCPRelayCnt.Store(ip+":"+strconv.Itoa(port), cnt.(int)+1)
default:
TCPRelayCnt.Store(ip+":"+strconv.Itoa(port), 0)
}
return true
})
}
// TCP step 3-2
func relayTCPRaw(data []byte, n int, remoteAddr net.Addr, key string) {
cnt, _ := TCPRecvCnt.Load(remoteAddr.String())
// check type for safety
switch cnt.(type) {
case int:
TCPRecvCnt.Store(remoteAddr.String(), cnt.(int)+1)
default:
TCPRecvCnt.Store(remoteAddr.String(), 0)
}
clientTCPIPs.Range(func(robotID,value interface{})bool{
if _, ok := clientTCPPorts.Load(robotID.(string)+":"+key); ok {
port, ok := clientTCPPorts.Load(robotID.(string)+":"+key)
if !ok {
fmt.Println("No key", robotID.(string)+":"+key, " in clientTCPPorts")
return true
}
address := value.(string)+":"+strconv.Itoa(port.(int))
if address == remoteAddr.String() {
return true
}
conn, ok := clientTCPSockets.Load(address)
if !ok {
return true
}
conn.(net.Conn).Write(data[:n])
cnt, _ := TCPRelayCnt.Load(remoteAddr.String())
// check type for safety
switch cnt.(type) {
case int:
TCPRelayCnt.Store(remoteAddr.String(), cnt.(int)+1)
default:
TCPRelayCnt.Store(remoteAddr.String(), 0)
}
}
return true
})
}
func FPSCounter() {
duration := time.Duration(time.Second)
t := time.NewTicker(duration)
defer t.Stop()
for {
<- t.C
var states []SocketState
clientUDPPorts.Range(func(key,socket interface{})bool{
recvCnt, ok := UDPRecvCnt.Load(key.(string))
if !ok {
fmt.Println("No key in UDP socket", key.(string))
return true
}
relayCnt, ok := UDPRelayCnt.Load(key.(string))
if !ok {
fmt.Println("No key in UDP socket", key.(string))
return true
}
_state, ok := UDPStateMap.Load(key.(string))
state := _state.(SocketState)
state.RecvFPS = recvCnt.(int)
state.RelayFPS = relayCnt.(int)
states = append(states, state)
newState := SocketState{Key:state.Key, Type:"UDP", IP: state.IP, Port: state.Port, RecvFPS:0, RelayFPS:0}
UDPStateMap.Store(key.(string), newState)
UDPRecvCnt.Store(key.(string), 0)
UDPRelayCnt.Store(key.(string), 0)
return true
})
clientTCPSockets.Range(func(key,socket interface{})bool{
recvCnt, ok := TCPRecvCnt.Load(key.(string))
if !ok {
fmt.Println("No key in TCP socket", key.(string))
return true
}
relayCnt, ok := TCPRelayCnt.Load(key.(string))
if !ok {
fmt.Println("No key in TCP socket", key.(string))
return true
}
_state, ok := TCPStateMap.Load(key.(string))
state := _state.(SocketState)
state.RecvFPS = recvCnt.(int)
state.RelayFPS = relayCnt.(int)
states = append(states, state)
newState := SocketState{Key:state.Key, Type:"TCP", IP: state.IP, Port: state.Port, RecvFPS:0, RelayFPS:0}
TCPStateMap.Store(key.(string), newState)
TCPRecvCnt.Store(key.(string), 0)
TCPRelayCnt.Store(key.(string), 0)
return true
})
mutex.Lock()
socketStates = states
mutex.Unlock()
}
}
func initTemplate(fileName string) (err error) {
myTemplate, err = template.ParseFiles(fileName)
checkErr(err)
return err
}
func webHandler(writer http.ResponseWriter, request *http.Request) {
data := make(map[string]interface{})
data["title"] = "Data Relay"
mutex.RLock()
data["states"] = socketStates
mutex.RUnlock()
myTemplate.Execute(writer, data)
}
func main() {
for key, port := range UDPPortsDict {
clientAddr := &net.UDPAddr{IP: net.IPv4zero, Port: port}
clientListener, err := net.ListenUDP("udp", clientAddr)
checkErr(err)
clientUDPSockets.Store(key, clientListener)
go readUDP(clientListener, key)
}
for key, port := range TCPPortsDict {
clientAddr, err := net.ResolveTCPAddr("tcp4", ":"+strconv.Itoa(port))
checkErr(err)
clientListener, err := net.ListenTCP("tcp", clientAddr)
checkErr(err)
go readTCP(clientListener, key)
}
go FPSCounter()
initTemplate("./index.html")
http.HandleFunc("/", webHandler)
err := http.ListenAndServe("0.0.0.0:8080", nil)
checkErr(err)
<-done
}