-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathserver.go
88 lines (72 loc) · 1.83 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
package ri
import (
"fmt"
"log"
"net"
"strings"
)
type Server struct {
MaxBuffSize int
clientDB map[string]NetworkInfo
conn *net.UDPConn
}
func NewServer() *Server {
s := new(Server)
s.clientDB = make(map[string]NetworkInfo)
s.MaxBuffSize = 2048
return s
}
type RIUpdateFunc func(ni *NetworkInfo, err error) (retErr error)
//Use ":10001" to listen port 10001
func (s *Server) ListenAndServe(port string, callback RIUpdateFunc) {
ServerAddr, err := net.ResolveUDPAddr("udp", port)
if err != nil {
log.Println("Server port init error:", err)
return
}
s.conn, err = net.ListenUDP("udp", ServerAddr)
if err != nil {
log.Println("Server listening error:", err)
return
}
defer s.conn.Close()
log.Println("UDP Server strating listen:", port)
buf := make([]byte, s.MaxBuffSize)
for {
n, addr, err := s.conn.ReadFromUDP(buf)
if err != nil {
fmt.Println("Error: ", err)
} else {
s.parseCmds(string(buf[0:n]), addr.String(), callback)
}
}
}
func (s *Server) routingInfo(cmd, addr string, callback RIUpdateFunc) {
ni, err := DecodeRoutingInfo(cmd)
if err != nil {
log.Println("DecodeRoutingInfo err=", err)
callback(nil, err)
return
}
ip, port := DecodeIpPort(addr)
ni.EIPv4 = ip
ni.EPort = port
s.clientDB[ni.Id] = *ni
log.Println("RoutingInfo work:", ni, " is it use NAT?", ni.UseNAT())
callback(ni, nil)
}
func (s *Server) parseCmds(cmd string, addr string, callback RIUpdateFunc) {
fmt.Println("Received ", cmd, " from ", addr)
if strings.Contains(cmd, CMD_RoutingInfo) {
log.Println("Cmd:", CMD_RoutingInfo)
s.routingInfo(cmd, addr, callback)
} else if strings.Contains(cmd, CMD_HolePunching) {
log.Println("Cmd:", CMD_HolePunching)
//TODO.
} else if strings.Contains(cmd, CMD_RequestPairing) {
log.Println("Cmd:", CMD_RequestPairing)
//TODO.
} else {
log.Println("Cmd invalid.")
}
}