-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathnet_socket.go
134 lines (108 loc) · 2.46 KB
/
net_socket.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
package litenetlib
import (
"log"
"fmt"
"net"
)
type NetSocket struct {
listener INetSocketListener
isRunningV4 bool
udpConnV4 *net.UDPConn
isRunningV6 bool
udpConnV6 *net.UDPConn
}
type INetSocketListener interface {
OnMessageReceived(numBytes int, buf []byte, addr *net.UDPAddr)
}
func (netSocket *NetSocket) BindV4(addr string, port int) error {
log.Printf("Binding V4 UDP socket: %s:%d", addr, port)
listenAddr, err := net.ResolveUDPAddr("udp4", fmt.Sprintf("%s:%d", addr, port))
if err != nil {
return err
}
udpConnV4, err := net.ListenUDP("udp4", listenAddr)
if err != nil {
return err
}
netSocket.udpConnV4 = udpConnV4
netSocket.isRunningV4 = true
go netSocket.receiveV4()
return nil
}
func (netSocket *NetSocket) BindV6(addr string, port int) error {
log.Printf("Binding V6 UDP socket: [%s]:%d", addr, port)
listenAddr, err := net.ResolveUDPAddr("udp6", fmt.Sprintf("[%s]:%d", addr, port))
if err != nil {
return err
}
udpConnV6, err := net.ListenUDP("udp6", listenAddr)
if err != nil {
return err
}
netSocket.udpConnV6 = udpConnV6
netSocket.isRunningV6 = true
go netSocket.receiveV6()
return nil
}
func (netSocket *NetSocket) receiveV4() {
var buf []byte
for {
if !netSocket.isRunningV4 {
break
}
buf = make([]byte, MAX_PACKET_SIZE)
numBytes, addr, err := netSocket.udpConnV4.ReadFromUDP(buf)
if err != nil {
continue
}
if numBytes == 0 {
continue
}
netSocket.listener.OnMessageReceived(numBytes, buf, addr);
}
}
func (netSocket *NetSocket) receiveV6() {
var buf []byte
for {
if !netSocket.isRunningV6 {
break
}
buf = make([]byte, MAX_PACKET_SIZE)
numBytes, addr, err := netSocket.udpConnV6.ReadFromUDP(buf)
if err != nil {
continue
}
if numBytes == 0 {
continue
}
netSocket.listener.OnMessageReceived(numBytes, buf, addr);
}
}
func (netSocket *NetSocket) Close() {
netSocket.CloseV4()
netSocket.CloseV6()
}
func (netSocket *NetSocket) CloseV4() {
netSocket.isRunningV4 = false
if netSocket.udpConnV4 == nil {
return
}
netSocket.udpConnV4.Close()
netSocket.udpConnV4 = nil
}
func (netSocket *NetSocket) CloseV6() {
netSocket.isRunningV6 = false
if netSocket.udpConnV6 == nil {
return
}
netSocket.udpConnV6.Close()
netSocket.udpConnV6 = nil
}
func (netSocket *NetSocket) IsListening() bool {
return netSocket.udpConnV4 != nil || netSocket.udpConnV6 != nil
}
func NewNetSocket(listener INetSocketListener) *NetSocket {
return &NetSocket{
listener: listener,
}
}