forked from openp2p-cn/gateway-lite
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathudpsession.go
89 lines (80 loc) · 1.54 KB
/
udpsession.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
package main
import (
"bytes"
"encoding/binary"
"encoding/json"
"net"
"time"
)
type UDPServer struct {
conn *net.UDPConn
la *net.UDPAddr
tm *time.Timer
}
type UDPSession struct {
conn *net.UDPConn
ra *net.UDPAddr
}
func newUDPServer(la *net.UDPAddr) (*UDPServer, error) {
conn, err := net.ListenUDP("udp", la)
if err != nil {
return nil, err
}
if la == nil {
la, _ = net.ResolveUDPAddr("udp", conn.LocalAddr().String())
}
sess := &UDPServer{
conn: conn,
la: la,
}
sess.start()
return sess, nil
}
func (sess *UDPServer) start() {
sess.tm = time.NewTimer(time.Second)
sess.tm.Stop()
go sess.run()
}
func (sess *UDPServer) run() {
for {
msg := make([]byte, 1600)
len, ra, e := sess.conn.ReadFromUDP(msg)
MsgQueue <- &msgContext{
sess: &UDPSession{
conn: sess.conn,
ra: ra,
},
msg: msg[:len],
}
if e != nil {
break
}
}
}
func (sess *UDPServer) stop() {
sess.conn.Close()
}
func (sess *UDPSession) write(mainType uint16, subType uint16, packet interface{}) error {
data, err := json.Marshal(packet)
if err != nil {
gLog.Printf(LvERROR, "marshal data failed:%s", err)
return err
}
// gLog.Println(LvINFO, "write packet:", string(data))
head := openP2PHeader{
uint32(len(data)),
mainType,
subType,
}
headBuf := new(bytes.Buffer)
err = binary.Write(headBuf, binary.LittleEndian, head)
if err != nil {
return err
}
writeBytes := append(headBuf.Bytes(), data...)
_, err = sess.conn.WriteToUDP(writeBytes, sess.ra)
return err
}
func (sess *UDPSession) close() error {
return nil
}